fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err("Division by zero".to_string());
}
Ok(a / b)
}
fn calculate(a: i32, b: i32) -> Result<i32, String> {
let result = divide(a, b)?;
Ok(result * 2)
}
fn main() {
let result = calculate(10, 5);
match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),
}
}
let result = divide(a, b)?;
类似于
let result = divide(a, b);
如果result 是 Err 就返回 Err, 否则就继续。是一个非常简便的写法。