Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include a variable in a String?

Tags:

rust

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.

like image 759
jrbobdobbs83 Avatar asked Mar 19 '26 02:03

jrbobdobbs83


1 Answers

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#).

like image 89
Exalted Toast Avatar answered Mar 21 '26 16:03

Exalted Toast