What is this reversal: sometimes it unfolds, sometimes it unwrap_or

Note. The specifics of this question regarding read_line and ~str apply to the rust version prior to version 1.0. The general concepts of unwrap and unwrap_or remain relevant.

I came across this while reading Rust for Rubyists ie:

 let mut reader = BufferedReader::new(io::stdin()); let input = reader.read_line().unwrap_or(~"nothing"); 
+57
rust
Jan 21 '14 at 12:06 on
source share
2 answers

Note. The specifics in this answer regarding read_line and ~str apply to Rust prior to version 1.0. The general concepts of unwrap and unwrap_or remain relevant.

Since read_line may fail, it returns Option<~str> . To get the value, you can use pattern matching or one of the reversal 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 value ("nothing" in this case)

+54
Jan 21 '14 at 12:21
source share

Note. The specifics in this answer regarding read_line and ~str apply to Rust prior to version 1.0. The general concepts of unwrap and unwrap_or remain relevant.

Rust has API documentation that explains these things.

BufferedReader.read_line :

fn read_line(&mut self) -> Option<~str>

Reads the next line of input, interpreted as a sequence of encoded Unicode codes encoded by UTF-8. If a new line is encountered, then the new line is contained in the returned line.

...

[Then something about raising the io_error condition, which is one situation in which it will return None if the condition is processed. If this is not the case, it will not work and you will never get anything.]

You will also get None if everything is read in the reader.




Option.unwrap :

fn unwrap(self) -> T

Derives a value from a parameter type and returns it.

It is useful primarily for retrieving strings, vectors, and unique pointers from parameter types without copying them.

...

I.e

  • Some(a).unwrap() returns a
  • None.unwrap() does not work



Option.unwrap_or :

fn unwrap_or(self, def: T) -> T

Returns the contained value or default value

I.e

  • Some(a).unwrap_or(b) returns a
  • None.unwrap_or(b) returns b
+78
Jan 21 '14 at 12:27
source share



All Articles