Mastodon Rust, How to convert String to Int and Int to String

Rust, How to convert String to Int and Int to String

String to Int

To convert a string (or a &str) to an integer in Rust, we can use the parse method:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // String to int
    let s1 = String::from("42");
    let n1 = s1.parse::<u64>()?;
    // or
    let n2: u64 = s1.parse()?;

    Ok(())
}

Int to String

On the other hand, converting an integer to an owned String can be achieved with the format! macro.

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let n2: u64 = 42;

    // int to string
    let s2 = format!("{}", n2);
    Ok(())
}

The code is on GitHub

As usual, you can find the code on GitHub: github.com/skerkour/kerkour.com (please don’t forget to star the repo 🙏)

Join the private club where I share exclusive tips and stories about programming, hacking and entrepreneurship. 1 message / week.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Want to learn Rust and offensive security? Take a look at my book Black Hat Rust. All early-access supporters get a special discount and awesome bonuses: https://academy.kerkour.com/black-hat-rust?coupon=BLOG.
Warning: this offer is limited in time!


Tags: rust, programming, tutorial

Related posts