Note The specifics in this question regarding
read_line
and~str
pertain to a pre-1.0 version of Rust. The general concepts aboutunwrap
andunwrap_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");
Because
read_line
might fail it returnsOption<~str>
. To get the value out you can use pattern matching or one of the unwrap methods.The difference between
unwrap
andunwrap_or
is thatunwrap
will fail if there is no value (None
) butunwrap_or
will return the specified default ("nothing" in this case)Rust has API documentation which explains these things.
BufferedReader.read_line
:You'll also get
None
returned if everything has been read in the reader.Option.unwrap
:That is,
Some(a).unwrap()
returnsa
None.unwrap()
failsOption.unwrap_or
:That is,
Some(a).unwrap_or(b)
returnsa
None.unwrap_or(b)
returnsb