Why does snippet pattern_matching_2
and pattern_matching_3
work whereas pattern_matching_1
doesn't? The compiler suggests that let &x = &foo
moves the string hello, which I'm aware of and don't see where the problem is -- I'm not using foo
anyway, and compiler doesn't complain anything about pattern_matching_3
, which moves the string hello as well.
The example snippets are adapted from this answer, which didn't answer my question.
The code snippets:
fn pattern_matching_1() {
let foo = String::from("hello");
let &x = &foo;
println!("{}", x);
}
fn pattern_matching_2() {
let foo = 12;
let &x = &foo;
println!("{}", x);
}
fn pattern_matching_3() {
let foo = String::from("hello");
let x = foo;
println!("{}", x);
}
The compiler error of pattern_matching_1
:
error[E0507]: cannot move out of a shared reference
--> src/main.rs:26:14
|
26 | let &x = &foo;
| -- ^^^^
| ||
| |data moved here
| |move occurs because `x` has type `String`, which does not implement the `Copy` trait
| help: consider removing the `&`: `x`