io::stdin()
實際上是一個BufferedReader<>
包裝stdin
。如您所見,in the docs,BufferedReader
提供了很多提取內容的方法。
你必須值得注意的是:
fn read_line(&mut self) -> IoResult<String>
將嘗試讀取從標準輸入線(也可能返回一個錯誤)。一個簡單的代碼來讀取int
從標準輸入將是:
let a: int = from_str(io::stdin().read_line().unwrap().as_slice()).unwrap()
但它沒有任何錯誤處理,並可以很容易失敗。
更明確的辦法將要求您更清潔處理事情:
let a: int = match from_str(
match io::stdin().read_line() {
Ok(txt) => txt, // Return the slice from_str(...) expects
Err(e) => { /* there was an I/O Error, details are in e */ }
}.as_slice()) /* match from_str(...) */ {
Some(i) => i, // return the int to be stored in a
None => { /* user input could not be parsed as an int */ }
};
Rust告訴我'txt'不夠長,無法在第二次執行的下一個塊中匹配,我怎麼能通過? – 2014-09-03 20:18:19
沒關係固定,as_slice()必須移動到第一個匹配語句的末尾 – 2014-09-03 20:28:10
@SyntacticFructose哦,是的,的確,好抓!我會糾正它。 – Levans 2014-09-03 20:46:08