2

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
  • 4,958
  • 4
  • 31
  • 39
jrbobdobbs83
  • 33
  • 1
  • 6

3 Answers3

6

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
  • 556
  • 4
  • 9
5

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

at54321
  • 4,634
  • 8
  • 23
1

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
  • 1,921
  • 21
  • 22