2014-01-22 18 views
2

我一直對Rust的std::fmt模塊中的plural功能感到困惑,但我需要一個具體的例子來使它真實。你如何在Rust中使用複數方法?

的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 

回答

3

的錯誤信息是相當混亂,但顯然你不能使用兩個格式字符串的參數都是相同的。也就是說,對於{:d}{0, plural, one{time} other{times}}都不能使用參數0(count)。

有可能通過將參數兩刀功能來解決這個限制:

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); 
+0

謝謝澄清!但它看起來像只適用於'uint'類型。第二個選項按照書面方式工作,但僅適用於uint,不適用於int。第一個選項不起作用,因爲'{:d}'用於簽名類型。可以用複數形式來處理帶符號的數字嗎? – quux00

相關問題