What is unwrap and unwrap_or in Rust?

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

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş