How do I include a variable in a String?
Solution 1:
In Rust, the go-to is string formatting.
fn main() {
let num = 1234;
let str = format!("Number here: {}", num);
println!("{}", str);
}
In most languages, the term for the concept is one of "string formatting" (such as in Rust, Python, or Java) or "string interpolation" (such as in JavaScript or C#).
Solution 2:
How to write formatted text to String
Just use format! macro.
fn main() {
let a = format!("test");
assert_eq!(a, "test");
let b = format!("hello {}", "world!");
assert_eq!(b, "hello world!");
let c = format!("x = {}, y = {y}", 10, y = 30);
assert_eq!(c, "x = 10, y = 30");
}
How to convert a single value to a string
Just use .to_string() method.
fn main() {
let i = 5;
let five = String::from("5");
assert_eq!(five, i.to_string());
}
Solution 3:
As of Rust 1.58, you can also write format!("Hey {num}")
. See this for more.