Converting an int to String in Rust
Alex Garella
8 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.
Using the to_string Method
Rust’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
} The format! Macro: A Flexible Approach
When 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
} Conclusion
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.