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

How to convert String to Int and Int to String in Rust

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 🙏)

1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: rust, programming, tutorial

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!

Related posts