【问题标题】:Is it possible to declare the type of the variable in Rust for loops?是否可以在 Rust for 循环中声明变量的类型?
【发布时间】:2018-05-02 18:59:47
【问题描述】:

C++ 示例:

for (long i = 0; i < 101; i++) {
    //...
}

在 Rust 中我尝试过:

for i: i64 in 1..100 {
    // ...
}

我可以轻松地在 for 循环之前声明一个 let i: i64 = var 但我宁愿学习正确的方法,但这导致

error: expected one of `@` or `in`, found `:`
 --> src/main.rs:2:10
  |
2 |     for i: i64 in 1..100 {
  |          ^ expected one of `@` or `in` here

【问题讨论】:

    标签: rust


    【解决方案1】:

    您可以在该范围内使用的文字之一上使用integer suffix。类型推断将完成剩下的工作:

    for i in 1i64..101 {
        println!("{}", i);
    }
    

    【讨论】:

    • 按照类型归属方法,range({ let x: i64 = 1; x }, 100) 也可以。当然,我不建议你真的这样做
    • 这可以用于自定义类型吗?那么元组中的元素呢?
    • 语言中内置了数字文字的后缀。我不知道您所说的“在元组中”是什么意思。当然,(1u64, 2f32) 工作得很好。也许问一个新问题会更好?
    • 真的应该可以做到for i: u8 in 0..26
    【解决方案2】:

    不,不可能for 循环中声明变量的类型。

    相反,一种更通用的方法(例如,也适用于enumerate())是通过解构循环主体内的项目来引入let 绑定。

    例子:

    for e in bytes.iter().enumerate() {
        let (i, &item): (usize, &u8) = e; // here
        if item == b' ' {
            return i;
        }
    }
    

    【讨论】:

    • 如果你想省略usize部分,你也可以使用(_, &amp;u8)
    【解决方案3】:

    如果您的循环变量恰好是返回泛型类型的函数调用的结果:

    let input = ["1", "two", "3"];
    for v in input.iter().map(|x| x.parse()) {
        println!("{:?}", v);
    }
    
    error[E0284]: type annotations required: cannot resolve `<_ as std::str::FromStr>::Err == _`
     --> src/main.rs:3:37
      |
    3 |     for v in input.iter().map(|x| x.parse()) {
      |                                     ^^^^^
    

    您可以使用 turbofish 来指定类型:

    for v in input.iter().map(|x| x.parse::<i32>()) {
    //                                   ^^^^^^^
        println!("{:?}", v);
    }
    

    或者您可以使用完全限定语法

    for v in input.iter().map(|x| <i32 as std::str::FromStr>::from_str(x)) {
    //                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        println!("{:?}", v);
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多