14th Jan 2022
The Rust 1.58.0
update today bought a very nice addition, this is a feature that’s often missed by the growing number of dynamic language users that are giving Rust a try, and it’s now available in stable!
It allows you to put variables from the outside scope directly into format string curly braces:
// In all examples below x = "world"
let x = "world";
println!("Hello {x}!");
Hello world!
You can also use format specifiers within the curly braces.
For example with debug output:
let items = vec![10, 20, 30];
println!("{items:?}")
[10, 20, 30]
Or pretty print the output:
println!("{items:#?}")
[
10,
20,
30,
]
If you haven’t seen it before, you can set the minimum width of how items are printed to give uniform spacing with :[width]
. Example to print a table with even spacing:
let items = ["these", "words", "are", "different", "sizes"];
let column1 = "item";
let column2 = "iter";
println!("{column1:10}| {column2}");
println!("----------------");
for (i, item) in items.iter().enumerate() {
println!("{item:10}: {i}");
}
item | iter
----------------
these : 0
words : 1
are : 2
different : 3
sizes : 4
Align items t