rofrol
rofrol

Reputation: 15276

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

I know that I can read one line and convert it to number in one line, i.e.

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

How to do the same without parse and in one line? Right now I do this:

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

Edit: Explanation what's going on here:

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

We can use trim on String, because String is a str decoreated with pointer, an owned string.

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

Upvotes: 0

Views: 1431

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

trim() returns an &str view of the String returned by unwrap(). You can't store this object because the owning String will no longer exist at the end of the statement. So just use to_string() to convert the &str back to a String.

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

Upvotes: 2

Related Questions