In Rust, you can convert an integer to a string using the to_string()
method or by using the format!
macro.
In this example,
num
and assign it a value of 42
.to_string()
method to convert the integer num
to a string and store the result in the string variable str_num
.to_string()
method converts the integer to its string representation.// Convert Integer to String using to_string()
fn main() {
let num = 42;
let str_num = num.to_string();
println!("String representation of integer: {}", str_num);
}
String representation of integer: 42
In this example,
negative_num
with a value of -10
.format!
macro to convert the negative integer negative_num
to a string and store the result in the string variable str_negative_num
.format!
macro provides a convenient way to format strings with variables.// Convert Negative Integer to String using format! Macro
fn main() {
let negative_num = -10;
let str_negative_num = format!("String representation of negative integer: {}", negative_num);
println!(str_negative_num);
}
String representation of negative integer: -10
In this tutorial, we learned How to Convert Integer to String in Rust language with well detailed examples.