HiveBrain v1.2.0
Get Started
← Back to all entries
debugrustMajor

What is unwrap and unwrap_or in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
unwrapandunwrap_orrustwhat

Problem

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 encountered this while reading Rust for Rubyists:
let mut reader = BufferedReader::new(io::stdin());
let input = reader.read_line().unwrap_or(~"nothing");


Sometimes it's unwrap, sometimes it's unwrap_or. What is unwrap and unwrap_or?

Solution

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. 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)

Context

Stack Overflow Q#21257686, score: 65

Revisions (0)

No revisions yet.