I think this should be simple, but my Google-fu is weak. I'm trying to build a String in Rust using a u32 variable. In C, I would use snprintf, like this:
Creating a char array in C using variables like in a printf
but I can't find anything on how to do it in Rust.
In Rust, the go-to is string formatting*.
fn main() {
let num = 1234;
let str = format!("Number here: {num}");
println!("str is \"{str}\"");
// Some types only support printing with debug formatting with :?
let vec = vec![1, 2, 3];
println!("vec is {vec:?}");
// Note that you can only inline variables.
// Values and expressions cannot be inlined:
println!("{} + {} = {}", 1, 2, 1 + 2);
}
Alternatively (applicable to older versions of Rust), you can write the variables after the string:
fn main() {
let num = 1234;
let str = format!("Number here: {}", num);
println!("str is \"{}\"", str);
}
While functionally equivalent, the default linter Clippy will suggest writing the first version when run in pedantic mode.
This doesn't always work, particularly if the variable doesn't support the default formatter. There are more details on string formatting in the docs, including more display settings and how to implement formatting for custom types.
* - 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#).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With