简体   繁体   English

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

[英]How do you use the plural method in Rust?

I've been puzzling over the plural functionality in Rust's std::fmt module, but I need a concrete example to make it real. 我一直在为Rust的std::fmt模块中的plural功能感到困惑,但是我需要一个具体的例子来使其真实。

The 0.9 documentation for it is half way down the page here: http://static.rust-lang.org/doc/0.9/std/fmt/index.html 它的0.9文档位于页面的一半以下: http : //static.rust-lang.org/doc/0.9/std/fmt/index.html

Is this intended to be useful to pluralize words? 这对使单词复数有用吗? For example, how would I use it to print: 例如,我将如何使用它进行打印:

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

I tried this, but I'm getting an error: 我试过了,但是出现错误:

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

The error message is quite confusing, but apparently you can not use the same parameter for both format strings. 该错误消息非常混乱,但是显然您不能对两个格式字符串使用相同的参数。 That is, you can not use the parameter 0 ( count ) for both {:d} and {0, plural, one{time} other{times}} . 也就是说,不能同时为{:d}{0, plural, one{time} other{times}}使用参数0( count )。

It is possible to work around this limitation by passing the parameter twice in the function: 通过在函数中两次传递参数,可以解决此限制:

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

Alternatively you can use # to put the value itself inside the plural formatting: 或者,您可以使用#将值本身放入plural格式内:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM