I'm new to Rust. I would like to know why &item can't be used in the second for loop below. I was expecting that with &item I'd get a mutable variable: item.
let mut collection = vec![1, 2, 3];
for &item in collection.iter() {} // ok
for &item in collection.iter_mut() {} // error: mismatched types expected `&mut {integer}` found `&_`
Looks like pattern matching won't work for mutable references?
Note that x and y have different values here because the &mut mut y destructuring moved the 1 out from behind the &mut x (which just copies the value because i32: Copy) and bound it to a new i32 variable, y.
Have a play with that playground link and see if you can predict what would happen if you changed various things.
I don't think this is technically an ambiguity - meaning, it's unambiguous according to the language grammar because we read the &mut first then look for either another pattern or the IdentifierPattern (i.e. ref? mut? ident) - but it's definitely unintuitive for a human.
Following the same rules, Rust-analyzer gives me this syntax tree for the &mut y version.
The parens do force a different parse tree for the second version, but the grammar rules appear to be ambiguous¹. In both cases, we're talking about a ReferencePattern which then contains an IdentifierPattern (both of which are alternates for PatternWithoutRange:
The ambiguity here lies in which of these two rules the mut belongs to. Substituting the IdentifierPattern rule into ReferencePattern gives us this construction:
As there is no ref token present, we have one mut token to match against (mut? mut?), and each of those positions carries a different semantic meaning.
¹ As long as that's a BNF-style (generative) grammar and not a PEG-style grammar