Rust 中Some特殊用法
发表时间:2022-06-20 09:55:05
阅读:527
描述: 一般说来Some都是带有一个关联值的枚举类型;这里: opt.map_or(Ok(None), |r| r.map(Some))
some 是什么用法?
use std::num::ParseIntError;
fn double_first(vec: Vec<&str>) -> Result<Option<i32>, ParseIntError> {
// vec.first():返回类型Option<&str>
// option<&str>.map(|first|) : first是 &str
//first.parse::<i32>(): 类型 result<i32,ParseIntError>
//Result<i32,ParseIntError>.map(|n|): n是i32, 返回值类型 Result<i32,ParseIntError>
let opt = vec.first().map(|first| {
first.parse::<i32>().map(|n| 2 * n)
});
//opt:Option<Result<i32,ParseIntError>>
//opt.map_or(): pub fn map_or<U, F>(self, default: U, f: F) -> U where F: FnOnce(T) -> U,
opt.map_or(Ok(None), |r| r.map(Some)) //这里返回什么类型?r| r.map(Some) 中的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));
}
期望:有理有据,尽量给出参考链接.
opt.map_or(Ok(None), |r| r.map(Some))
应该等价于
返回的就是函数签名里的Result<Option, ParseIntError>,Some用于直接构造一个值为Some(a)的Option