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

后端 未结 2 1427
我在风中等你
我在风中等你 2020-12-24 00:11

Note The specifics in this question regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts

相关标签:
2条回答
  • 2020-12-24 00:44

    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
    0 讨论(0)
  • 2020-12-24 00:59

    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)

    0 讨论(0)
提交回复
热议问题