I do not know why the code is error?
let [mut x] = &[()]; //~ ERROR
let [ref x] = &[()]; //~ ERROR
let [ref mut x] = &mut [()]; //~ ERROR
Before the 2024 edition, using ref
and mut
works in patterns with ref
and ref mut
binding modes. But in the 2024 edition, you can only use these keywords in move
binding mode:
You can convert your patterns to move
binding mode by adding the leading reference:
fn main() {
let &[mut x] = &[()];
let &[ref x] = &[()];
let &mut [ref mut x] = &mut [()];
}
6 Likes
The reason why the rules were restricted in this way is so that the meaning of each one is clearer. Previously, you could, for example, add mut
and find that you lost a reference, because it overwrote the default binding mode, and this confused people. Now, it is always the case that:
mut
adds mutability to an otherwise immutable binding.ref
orref mut
makes the binding reference instead of move the input.- All 3 are always different from if you wrote nothing.
6 Likes