- 常见处理方式:
- 传播错误:使用
?
操作符将错误从闭包内部传播到调用闭包的函数中。
- 在闭包内处理错误:使用
match
表达式或者if let
表达式来处理Result
类型,根据Ok
和Err
的不同情况进行不同的操作。
- 示例代码:
fn process_with_closure() -> Result<i32, String> {
let closure = |input: i32| -> Result<i32, String> {
if input < 0 {
Err("Input cannot be negative".to_string())
} else {
Ok(input * 2)
}
};
let result = closure(5)?;
Ok(result)
}
fn handle_error_in_closure() {
let closure = |input: i32| {
match input {
num if num < 0 => {
println!("Error: Input cannot be negative");
0
}
_ => input * 2,
}
};
let result = closure(-3);
println!("Result: {}", result);
}