这是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`
答案 0 :(得分:2)
.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);
}
编辑:另请参阅this blog post,了解有关turbfish操作员的更多信息。