我正在学习 Rust by Example,但在 这个例子 中使用的美元符号 $
并不清楚:
// 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);
我在 Rust语言标准库文档中的
std::fmt
发现了这篇文章,但是它并没有解决我的问题: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 '$'
我稍微查看了一下代码,发现没有美元符号就无法编译通过,但是"width
"可以替换为任何标识符。也就是说,以下代码等价于第一个代码块的第三行:
println!("{number:>test$}", number=1, test=6);
myValue$
指定宽度?其次,为什么println!("{number:0>#width$}", number=-19, width=6);
打印出000-19
而println!("{number:#>0width$}", number=-19, width=6);
则打印-00019
,而println!("{number:#>width$}", number=-19, width=6);
则打印出###-19
?谢谢! - Fred$
指定了myValue
是宽度。 000-19 - 你使用0
来填充,不考虑符号,填充到6个字符。 -00019 - 你填充到6个字符并考虑符号(在这些情况下,#
没有意义)。 ###-19 - 你使用#
填充到6个字符,不考虑符号。 - Shepmaster0>
中,0
是fill
字符,而在>0
中,0
是['0']
的format_spec
。然而,我相信$
标记参数作为参数,如规范所述:parameter := argument '$'
。它可能是宽度,但也可能是精度,就像你的例子{number:.prec$}
一样。 - Fred