What does the dollar syntax mean in a Rust format string?

Viewed 1710

I'm going through Rust by Example and the use of $ (the dollar sign) in this example isn't clear to me:

// You can right-align text with a specified width. This will output
// "     1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);

// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);

I found this in the documentation for std::fmt, but it doesn't clarify things for me:

format_string := <text> [ maybe-format <text> ] *
maybe-format := '{' '{' | '}' '}' | <format>
format := '{' [ argument ] [ ':' format_spec ] '}'
argument := integer | identifier

format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]
fill := character
align := '<' | '^' | '>'
sign := '+' | '-'
width := count
precision := count | '*'
type := identifier | ''
count := parameter | integer
parameter := argument '$'

Poking around at the code a bit, I've found that it doesn't compile without the dollar sign, but "width" can be replaced with any arbitrary identifier. i.e. the following is equivalent to the third line in the first code block:

println!("{number:>test$}", number=1, test=6);
1 Answers
Related