Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this unwrap thing: sometimes it's unwrap sometimes it's unwrap_or

Tags:

rust

Note The specifics in this question regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts about unwrap and unwrap_or remain 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");
like image 482
rofrol Avatar asked Jan 21 '14 12:01

rofrol


2 Answers

Note The specifics in this answer regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts about unwrap and unwrap_or remain 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_error condition, which is one situation in which it would return None—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) -> T

Moves 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() fails

Option.unwrap_or:

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

Returns the contained value or a default

That is,

  • Some(a).unwrap_or(b) returns a
  • None.unwrap_or(b) returns b
like image 182
Chris Morgan Avatar answered Nov 02 '22 23:11

Chris Morgan


Note The specifics in this answer regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts about unwrap and unwrap_or remain 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)

like image 64
Arjan Avatar answered Nov 03 '22 00:11

Arjan