Only if you want it to.
#[derive(Default)]
struct Foo {
…
}
struct Bar {
…
}
fn do_something(foo: Foo) -> Bar {
# do something with Foo and return a Bar
…
}
fn main() {
let opt_foo: Option<Foo> = None;
// panics
let foo: Foo = opt_foo.unwrap();
// panics, but with an error message of your choosing
let foo: Foo = opt_foo.expect("foo was supposed to be there");
// converts the Option (Some or None) to a Result (Ok or Err,
// where Err can contain an error type or message and then passed
// around or returned or whatever)
let foo: Result<Foo> = opt_foo.ok_or("foo was supposed to be there");
// replaces it with a value of your choosing if it's not there
let foo: Foo = opt_foo.unwrap_or(Foo { … });
// replaces it with the default value the type defines
let foo: Foo = opt_foo.unwrap_or_default();
// keeps it as `None`, or if it's actually something then
// replaces the internal contents with the result of the
// function call
let bar: Option<Bar> = opt_foo.map(do_something);
// does arbitrary logic in the match arm if foo is there
match opt_foo {
Some(foo) => { do something with foo },
None => { do something else },
}
}
There are a few dozen other things you can do with an Option that handle the rarer use-cases, but the above are like 95%+ of what you want.