Alex Garella
8th September 2023
Rust offers efficient ways to handle data type conversions. One such common task is converting an integer to a string. Let's dive into how to do this.
to_string
MethodRust's standard library provides the direct method to_string()
for this purpose.
fn main() {
let num = 42;
let num_as_string = num.to_string();
println!("{}", num_as_string); // Outputs: 42
}
format!
Macro: A Flexible ApproachWhen you need more control over formatting, the format!
macro comes in handy.
fn main() {
let num = 42;
let num_as_string = format!("Number: {}", num);
println!("{}", num_as_string); // Outputs: Number: 42
}
With these two straightforward methods, Rust ensures integer-to-string conversions are intuitive and efficient.
Whether you opt for the to_string()
method or the format!
macro, Rust has you covered.