在一行代码中从 stdin 读取一行到一个字符串

Read a single line from stdin to a string in one line of code

我知道我可以读取一行并在一行中将其转换为数字,即

let lines: u32 = io::stdin().read_line().ok().unwrap().trim().parse().unwrap();

如何在不解析的情况下在一行中做同样的事情?现在我这样做:

let line_u = io::stdin().read_line().ok().unwrap();
let line_t = line_u.as_slice().trim();

编辑:解释这里发生了什么:

pub fn stdin() -> StdinReader
fn read_line(&mut self) -> IoResult<String> // method of StdinReader
type IoResult<T> = Result<T, IoError>;
fn ok(self) -> Option<T>                    // method of Result
fn unwrap(self) -> T                        // method of Option
fn trim(&self) -> &str                      // method of str from trait StrExt
fn to_string(?) -> String // I don't know where is this located in documentation

我们可以在 String 上使用 trim,因为 String 是一个用指针装饰的 str,一个拥有的字符串。

parse(), stdin(), read_line(), IoResult, ok(), unwrap(), trim(), str

trim() returns unwrap() 返回的 String&str 视图。您无法存储此对象,因为拥有的 String 将在语句末尾不再存在。所以只需使用 to_string()&str 转换回 String.

let line = io::stdin().read_line().ok().unwrap().trim().to_string();