Does Rust support Ruby-like string interpolation?

eonil picture eonil · Jan 24, 2014 · Viewed 10.5k times · Source

In Ruby I could do this.

aaa = "AAA"
bbb = "BBB #{aaa}"

puts(bbb)

> "BBB AAA"

The point of this syntax is eliminating repetition, and making it to feel like a shell script - great for heavy string manipulation.

Does Rust support this? Or have plan to support this? Or have some feature which can mimic this?

Answer

Dietrich Epp picture Dietrich Epp · Jan 24, 2014

Rust has string formatting.

fn main() {
    let a = "AAA";
    let b = format!("BBB {}", a);
    println(b);
}
// output: BBB AAA

In the Rust version, there is no additional repetition but you must explicitly call format!() and the inserted values are separated from the string. This is basically the same way that Python and C# developers are used to doing things, and the rationale is that this technique makes it easier to localize code into other languages.

The Rust mailing list has an archived discussion ([rust-dev] Suggestions) in which the different types of string interpolation are discussed.