Note The specifics in this question regarding
read_lineand~strpertain to a pre-1.0 version of Rust. The general concepts aboutunwrapandunwrap_orremain relevant.
I've encountered it while reading Rust for Rubyists i.e.:
let mut reader = BufferedReader::new(io::stdin());
let input = reader.read_line().unwrap_or(~"nothing");
Note The specifics in this answer regarding
read_lineand~strpertain to a pre-1.0 version of Rust. The general concepts aboutunwrapandunwrap_orremain relevant.
Rust has API documentation which explains these things.
BufferedReader.read_line:
fn read_line(&mut self) -> Option<~str>Reads the next line of input, interpreted as a sequence of UTF-8 encoded unicode codepoints. If a newline is encountered, then the newline is contained in the returned string.
…
[Then something about raising the
io_errorcondition, which is one situation in which it would returnNone—if the condition is handled. If it's not it'll fail and so you'll never get anything back.]
You'll also get None returned if everything has been read in the reader.
Option.unwrap:
fn unwrap(self) -> TMoves a value out of an option type and returns it.
Useful primarily for getting strings, vectors and unique pointers out of option types without copying them.
…
That is,
Some(a).unwrap() returns a
None.unwrap() failsOption.unwrap_or:
fn unwrap_or(self, def: T) -> TReturns the contained value or a default
That is,
Some(a).unwrap_or(b) returns a
None.unwrap_or(b) returns b
Note The specifics in this answer regarding
read_lineand~strpertain to a pre-1.0 version of Rust. The general concepts aboutunwrapandunwrap_orremain relevant.
Because read_line might fail it returns Option<~str>. To get the value out you can use pattern matching or one of the unwrap methods.
The difference between unwrap and unwrap_or is that unwrap will fail if there is no value (None) but unwrap_or will return the specified default ("nothing" in this case)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With