ZetCode

Rust int to string

last modified October 18, 2023

In this article we show how to convert integers to strings in Rust.

Integer to string conversion is a type conversion or type casting, where an entity of integer data type is changed into string one.

Rust int to string using to_string

The to_string function converts the integer value to a string.

main.rs
fn main() {

    let val = 4;
    let s1 = String::from("There are "); 
    let s2 = String::from(" hawks");
    
    let msg = s1 + &val.to_string() + &s2;

    println!("{}", msg)
}

In the program, we build a message from two strings and an integers. The integer is converted to a string with to_string.

λ rustc main.rs  
λ ./main.exe
There are 4 hawks

We compile and run the program.

Rust int to string with format!

We can do the conversion with the format! macro. It creates a String using interpolation of runtime expressions.

main.rs
fn main() {

    let val = 4;
    let msg = format!("There are {val} hawks");

    println!("{}", msg)
}

We build the message with the format! macro.

In this article we have performed int to string conversion in Rust.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.