jrbobdobbs83
jrbobdobbs83

Reputation: 133

How do I include a variable in a String?

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.

Upvotes: 10

Views: 23858

Answers (3)

Exalted Toast
Exalted Toast

Reputation: 819

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

Upvotes: 26

at54321
at54321

Reputation: 11708

As of Rust 1.58, you can also write format!("Hey {num}"). See this for more.

Upvotes: 14

iuridiniz
iuridiniz

Reputation: 2423

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());
}

Upvotes: 5

Related Questions