Rust newbie compile error (for (key: String, value: String) in | ^ expected one of `)`, `,`, `@`, or `|`)

51 Views Asked by At

I just read through the first three chapters of the Rust Programming Language, and am currently trying to apply my limited knowledge building a CLI weather app with the help of a YouTube tutorial.

I mostly have little idea what I'm doing, but just wanted to make something to inspire learning momentum.

May someone share some explanations on what I did wrong?

I tried compiling Rust code and failed with a syntax error.

fn main() {
    for (x: String, ) in [("hello".into(),)] {}
}
error: expected one of `)`, `,`, `@`, or `|`, found `:`
 --> src/main.rs:2:11
  |
2 |     for (x: String, ) in [("hello".into(),)] {}
  |           ^ expected one of `)`, `,`, `@`, or `|`

error: could not compile `forecast` (bin "forecast") due to 1 previous error

Playground

1

There are 1 best solutions below

0
Masklinn On

May someone share some explanations on what I did wrong?

As Ivan C commented, you can't have types inside patterns, which is why the left hand side of a for is. Nor does for support type annotations (as you can see -- or not see -- in the link above), so if you update the code to what you'd find in a let for instance:

for (x,): (String,) in [("hello".into(),)] {}

you will get

  |
2 |     for (x,): (String,) in [("hello".into(),)] {}
  |             ^ --------- specifying the type of a pattern isn't supported

There are two solutions to this:

  1. ensure the value is typed, instead of using "hello".into() you can use String::from("hello") or "hello".to_string(), that will ensure the value is correctly typed and solve the issue

  2. use iterators, as those take functions, which can be typed:

    [("hello".into(),)].into_iter().for_each(|(x,): (String,)| {})
    

I would personally recommend the former.

Or really you could just iterate on the &str themselves, it works fine, and only convert to a String if ans where needed.