【问题标题】:Read a single line from stdin to a string in one line of code在一行代码中从标准输入读取一行到一个字符串
【发布时间】:2015-01-15 20:47:09
【问题描述】:

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

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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 2013-01-11
      • 1970-01-01
      相关资源
      最近更新 更多