环境
- Rust 1.56.1
- VSCode 1.61.2
概念
参考:https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/option_result.html
示例
返回 Option
use std::num::ParseIntError;
fn double_first(vec: Vec<&str>) -> Option<Result<i32, ParseIntError>> {
vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n))
}
fn main() {
let numbers = vec!["42", "93", "18"];
let empty = vec![];
let strings = vec!["tofu", "93", "18"];
println!("The first doubled is {:?}", double_first(numbers));
println!("The first doubled is {:?}", double_first(empty));
println!("The first doubled is {:?}", double_first(strings));
}
返回 Result
use std::num::ParseIntError;
fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
let opt = vec.first().map(|first| first.parse::<i32>().map(|n| 2 * n));
opt.map_or(Ok(None), |r| r.map(Some))
}
fn main() {
let numbers = vec!["42", "93", "18"];
let empty = vec![];
let strings = vec!["tofu", "93", "18"];
println!("The first doubled is {:?}", double_first(numbers));
println!("The first doubled is {:?}", double_first(empty));
println!("The first doubled is {:?}", double_first(strings));
}
总结
了解了 Rust 中处理 Option 和 Result 同时存在的情况。
附录
|
请发表评论