Extracting the content of an Option

Hi,
I was wondering if there was a better (shorter or more idiomatic) way of extracting the value inside an Option or returning from the function if it has None. Here's what I usually do:

let result = match some_function_call(some_parameters) {
    Some (x) => x,
    None => return Err(String("Some error")),
};

It works perfectly fine, but it feels a bit verbose, and the 'Some(x)=>x' feels weird to me somehow.
(I can't use expect() because I don't want to panic on None)

Thanks!
Jonathan

You can do

let result = some_function_call(some_parameters).ok_or_else(|| String::from("Some error"))?;

Even better, the following should work, too, because ?-operator supports an implicit From conversion

let result = some_function_call(some_parameters).ok_or("Some error")?;

If your function also returns an Option you can just use the ? operator.

fn do_stuff() -> Option<String> {
  let some_parameters = some_function_call()?;

  ...
}

The two pieces here are

Thanks!

I saw ok_or_else in the docs, but didn't think of combining it with the ? operator
That's much cleaner.

It really shouldn't. There's nothing wrong with returning the associated value of an enum variant.