Is it possible to declare the type of the variable in Rust for loops?

后端 未结 3 1068
清歌不尽
清歌不尽 2020-12-03 16:30

C++ example:

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

In Rust I tried:

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


        
相关标签:
3条回答
  • 2020-12-03 17:11

    No, it is not possible to declare the type of the variable in a for loop.

    Instead, a more general approach (e.g. applicable also to enumerate()) is to introduce a let binding by destructuring the item inside the body of the loop.

    Example:

    for e in bytes.iter().enumerate() {
        let (i, &item): (usize, &u8) = e; // here
        if item == b' ' {
            return i;
        }
    }
    
    0 讨论(0)
  • 2020-12-03 17:20

    You can use an integer suffix on one of the literals you've used in the range. Type inference will do the rest:

    for i in 1i64..101 {
        println!("{}", i);
    }
    
    0 讨论(0)
  • 2020-12-03 17:28

    If your loop variable happens to be the result of a function call that returns a generic type:

    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()) {
      |                                     ^^^^^
    

    You can use a turbofish to specify the types:

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

    Or you can use the fully-qualified syntax:

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

    See also:

    • How do I imply the type of the value when there are no type parameters or ascriptions?
    0 讨论(0)
提交回复
热议问题