Rust has a question mark operator than can be used like this:
fn make_foo() -> Option<Foo> { ... }
fn make_bar() -> Option<Bar> {
let foo = make_foo()?;
// ... Many lines of code using `foo` to compute data for `Bar::make` ...
Some(Bar::make(...))
}
But what if I want a function returning Bar rather than Option<Bar> (thus retuning Bar::new instead of None when make_foo() returns None)?
Of course, I could do
fn make_bar() -> Bar {
match make_foo() {
None => { Bar::new() }
Some(foo) => {
// ... Many lines of code using `foo` to compute data for `Bar::make` ...
Bar::make(...)
}
}
}
but this increases nesting level for the entire function, which I do not like. I would like to have a replacement for the ? operator.
So I came up with
fn make_bar() -> Bar {
let foo = match make_foo() {
None => { return Bar::new(); }
Some(v) => v
};
// ... Many lines of code using `foo` to compute data for `Bar::make` ...
Bar::make(...)
}
Is this idiomatic Rust? Or are there better solutions?