Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust support Ruby-like string interpolation?

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?

like image 467
eonil Avatar asked Jan 24 '14 04:01

eonil


People also ask

What is Ruby string interpolation?

10 months ago. by John Otieno. String interpolation refers to the process of adding placeholders that reference other values in a string object. The values interpolated into a string are evaluated to their corresponding values.

Can I use string interpolation?

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.


2 Answers

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.

like image 101
Dietrich Epp Avatar answered Sep 21 '22 09:09

Dietrich Epp


RFC 2795 has been accepted, but not yet implemented. The proposed syntax:

let (person, species, name) = ("Charlie Brown", "dog", "Snoopy");  // implicit named argument `person` print!("Hello {person}");  // implicit named arguments `species` and `name` format!("The {species}'s name is {name}."); 

I hope to see it soon.

like image 35
eonil Avatar answered Sep 20 '22 09:09

eonil