你如何在Rust中使用复数方法?

时间:2014-01-22 03:31:31

标签: rust

我一直在为Rust的plural模块中的std::fmt功能感到困惑,但我需要一个具体的例子才能让它成为现实。

它的0.9文档位于页面的下半部分:http://static.rust-lang.org/doc/0.9/std/fmt/index.html

这是否有助于复数词?例如,我将如何使用它来打印:

This page has been visited 0 times.
This page has been visited 1 time.
This page has been visited 2 times.

我尝试了这个,但是我收到了一个错误:

fn main() {
    let mut count = 0;
    let s1 = format!("This page has been visited {:d} {0, plural, one{time} other{times}}.", count);
    println(s1);
}

error: argument used to format with `d` was attempted to not be used for formatting

1 个答案:

答案 0 :(得分:3)

错误消息非常混乱,但显然您不能对两个格式字符串使用相同的参数。也就是说,您不能对count{:d}使用参数0({0, plural, one{time} other{times}})。

可以通过在函数中传递参数两次来解决此限制:

let s1 = format!("This page has been visited {:d} {1, plural, one{time} other{times}}.", count, count);

或者,您可以使用#将值本身置于plural格式中:

let s1 = format!("This page has been visited {0, plural, one{# time} other{# times}}.", count);