6

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.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
jrbobdobbs83
  • 103
  • 1
  • 1
  • 9

3 Answers3

16

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

Exalted Toast
  • 656
  • 5
  • 12
14

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

at54321
  • 8,726
  • 26
  • 46
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());
}
iuridiniz
  • 2,213
  • 24
  • 26