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

时间:2017-09-18 14:52:20

标签: rust string-formatting

我正在通过示例查看Rust,并且$(美元符号)in this 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);

我在the documentation for 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);

1 个答案:

答案 0 :(得分:5)

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

The documentation says

  

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

// 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);
     

引用带有美元语法的参数不会影响   “下一个参数”计数器,所以通常一个好主意   按位置的参数,或使用命名参数。

also says

  

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

     
      
  1. 整数或名称后跟美元符号.N$

         

    使用格式参数N(必须是usize)作为精度。

  2.         

    例如,以下调用都打印相同的内容Hello x is 0.01000

    println!("Hello {0} is {1:.5}", "x", 0.01);
    println!("Hello {1} is {2:.0$}", 5, "x", 0.01);
    println!("Hello {0} is {2:.1$}", "x", 5, 0.01);
    println!("Hello {} is {:.*}",    "x", 5, 0.01);
    println!("Hello {} is {2:.*}",   "x", 5, 0.01);
    println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01);