Rust 有一个问号运算符,可以像这样使用:
这是合乎惯用法的Rust代码吗?还是有更好的解决方案?
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(...))
}
但如果我想要一个返回Bar
而不是Option<Bar>
的函数呢(因此在make_foo()
返回None
时返回Bar::new
而不是None
)?
当然,我可以这样做:
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(...)
}
}
}
但是这会增加整个函数的嵌套级别,我不喜欢这样。我想要一个替代 ?
操作符的方法。
所以我想到了下面这个:
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(...)
}
这是合乎惯用法的Rust代码吗?还是有更好的解决方案?
let
...else
稳定下来后,可能会有一种更简洁的方式。 - user3840170