我应该如何在Rust中键入annotate collect()(错误[E0282])? [重复]

问题描述 投票:0回答:1

以下是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);
}

playground

我怎样才能重写它,以便unwrap与其他运营商在一个链中?

如果我只是添加unwrap()(到该运算符链)我收到一个编译错误:

error[E0282]: type annotations needed, cannot infer type for `B`
rust
1个回答
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);
}

编辑:有关turbofish运算符的更多信息,另请参阅this blog post

© www.soinside.com 2019 - 2024. All rights reserved.