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()?;


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

The code is on GitHub

As usual, you can find the code on GitHub:

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: programming, rust, tutorial

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!