这个问题在这里已有答案:
以下是Rust by Example的修改示例:
fn main() {
// let strings = vec!["tofu", "93", "18"];
let strings = vec!["93", "18"];
let possible_numbers: Result<Vec<i32>, std::num::ParseIntError> = strings
.into_iter()
.map(|s| s.parse::<i32>())
.collect();
let possible_numbers = possible_numbers.unwrap();
// [93, 18]
println!("Results: {:?}", possible_numbers);
}
我怎样才能重写它,以便unwrap
与其他运营商在一个链中?
如果我只是添加unwrap()
(到该运算符链)我收到一个编译错误:
error[E0282]: type annotations needed, cannot infer type for `B`
在这种情况下,.collect()
需要一个类型注释。如果它无法从注释到变量(当它隐藏在展开后面时无法获取),则需要使用添加类型注释的turbofish样式。以下代码有效:(playground link)
fn main() {
// let strings = vec!["tofu", "93", "18"];
let strings = vec!["93", "18"];
let possible_numbers = strings
.into_iter()
.map(|s| s.parse::<i32>())
.collect::<Result<Vec<i32>, std::num::ParseIntError>>()
.unwrap();
println!("Results: {:?}", possible_numbers);
}
编辑:有关turbofish运算符的更多信息,另请参阅this blog post。