是否可以使用'?'范围内的运算符?
Is it possible to use '?' operator in a scope?
我多次观察到一种情况,我可能想根据一堆操作的最终结果采取行动,我不关心哪个操作引发了错误,只关心其中一个操作引发了错误,或者none 他们做到了。
我可以为此使用 ?
运算符,但它随后会将错误传播到函数调用。我希望这样的事情会奏效:
fn do_something() {
let i = {
let w = function1()?;
let x = function2(z)?.function3()?;
x.y()?
};
if let Ok(item) = i {
// ..
} else {
// call to some other function or something..
}
// some more code here..
}
但是,这不起作用。有没有其他方法可以实现这种模式?
我知道我可以将作用域包裹在闭包中,但这感觉很丑陋且不合常理,尤其是在经常需要这种行为的情况下。
这可能表明我需要将函数分解为更小的函数,但是在
这样的情况下证明这很笨拙
let i = {
function1()?.function2()?.function3()
}
制作一个全新的功能不太有意义。
也许这甚至不是惯用的做事方式。如果是这样,我应该如何处理这个问题?
您的示例无法真正重现,因为它无法编译。所以我会举一个我自己的例子。
您可以使用函数式方法来编写方法调用。像这样:
fn main() {
let result = one()
.and_then(|_ok| two())// will be called if one() returned Ok, otherwise `result will contain the returned Err
.and_then(|_ok| three()); // will be called if two() returned Ok, otherwise `result will contain the returned Err
println!("Result: {:#?}", result);
}
fn one() -> Result<(), String> {
println!("one");
Ok(())
}
fn two() -> Result<(), String> {
println!("two");
Err("two".to_owned())
}
fn three() -> Result<(), String> {
println!("tree"); // won;t be called because `two()` returned an err
Ok(())
}
我多次观察到一种情况,我可能想根据一堆操作的最终结果采取行动,我不关心哪个操作引发了错误,只关心其中一个操作引发了错误,或者none 他们做到了。
我可以为此使用 ?
运算符,但它随后会将错误传播到函数调用。我希望这样的事情会奏效:
fn do_something() {
let i = {
let w = function1()?;
let x = function2(z)?.function3()?;
x.y()?
};
if let Ok(item) = i {
// ..
} else {
// call to some other function or something..
}
// some more code here..
}
但是,这不起作用。有没有其他方法可以实现这种模式? 我知道我可以将作用域包裹在闭包中,但这感觉很丑陋且不合常理,尤其是在经常需要这种行为的情况下。 这可能表明我需要将函数分解为更小的函数,但是在
这样的情况下证明这很笨拙 let i = {
function1()?.function2()?.function3()
}
制作一个全新的功能不太有意义。 也许这甚至不是惯用的做事方式。如果是这样,我应该如何处理这个问题?
您的示例无法真正重现,因为它无法编译。所以我会举一个我自己的例子。
您可以使用函数式方法来编写方法调用。像这样:
fn main() {
let result = one()
.and_then(|_ok| two())// will be called if one() returned Ok, otherwise `result will contain the returned Err
.and_then(|_ok| three()); // will be called if two() returned Ok, otherwise `result will contain the returned Err
println!("Result: {:#?}", result);
}
fn one() -> Result<(), String> {
println!("one");
Ok(())
}
fn two() -> Result<(), String> {
println!("two");
Err("two".to_owned())
}
fn three() -> Result<(), String> {
println!("tree"); // won;t be called because `two()` returned an err
Ok(())
}