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

后端 未结 3 1085
清歌不尽
清歌不尽 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: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::()) {
    //                                   ^^^^^^^
        println!("{:?}", v);
    }
    

    Or you can use the fully-qualified syntax:

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

    See also:

    • How do I imply the type of the value when there are no type parameters or ascriptions?

提交回复
热议问题