Rust格式字符串中的美元语法是什么意思?

Fre*_*red 7 string-formatting rust

我将通过示例进行Rust,在这个示例中使用$(美元符号)对我来说并不清楚:

// 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);
Run Code Online (Sandbox Code Playgroud)

我在文档中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 '$'
Run Code Online (Sandbox Code Playgroud)

稍微调整一下代码,我发现没有美元符号就不能编译,但" width"可以用任意标识符替换.即以下等同于第一个代码块中的第三行:

println!("{number:>test$}", number=1, test=6);
Run Code Online (Sandbox Code Playgroud)

She*_*ter 6

它允许将另一个格式化项的宽度或精度作为参数提供,而不是作为格式字符串的一部分进行硬编码.可以使用数字索引或名称指定参数.

文件说:

usize通过使用美元语法指示第二个参数是usize指定宽度,宽度值也可以在参数列表中作为a提供,例如:

// All of these print "Hello x    !"
println!("Hello {:5}!", "x");
println!("Hello {:1$}!", "x", 5);
println!("Hello {1:0$}!", 5, "x");
println!("Hello {:width$}!", "x", width = 5);
Run Code Online (Sandbox Code Playgroud)

引用带有美元语法的参数不会影响"下一个参数"计数器,因此通过位置引用参数或使用命名参数通常是个好主意.

它还:

有三种可能的方法来指定所需的精度:

  1. 整数或名称后跟美元符号precision:

    使用格式参数N(必须是a .N$)作为精度.

例如,以下调用都打印相同的东西N:

// Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)}
println!("Hello {0} is {1:.5}", "x", 0.01);

// Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)}
println!("Hello {1} is {2:.0$}", 5, "x", 0.01);

// Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)}
println!("Hello {0} is {2:.1$}", "x", 5, 0.01);

// Hello {next arg ("x")} is {second of next two args (0.01) with precision
//                          specified in first of next two args (5)}
println!("Hello {} is {:.*}",    "x", 5, 0.01);

// Hello {next arg ("x")} is {arg 2 (0.01) with precision
//                          specified in its predecessor (5)}
println!("Hello {} is {2:.*}",   "x", 5, 0.01);

// Hello {next arg ("x")} is {arg "number" (0.01) with precision specified
//                          in arg "prec" (5)}
println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);
Run Code Online (Sandbox Code Playgroud)