I just finished reading the Rust book. I've had the following question right from the first few chapters and was hoping that it be would explained later in the book, but that quite didn't happened.
Why does adding an &
to the for
loop's pattern matcher cause Rust to attempt to move
instead of just match? Please see the source code below for an example.
#[derive(Debug)]
struct Structure(i32);
fn main() {
let arr = [Structure(1), Structure(2)];
// Manually going through the iterator
let mut iter = arr.iter();
let first: &Structure = iter.next().unwrap();
let first_ref: &&Structure = &first; // Taking a reference to a reference
println!("{:?}", first_ref); // Works as expected
for elem in arr.iter() { // Here elem is of type &Structure
print!("{:?}", elem);
}
println!("");
// The following code does not compile.
// for &elem in arr.iter() {
// print!("{:?}", elem);
// }
// println!("");
// This is the error that I get
// data moved here
// move occurs because `elem` has type `Structure`, which does not implement the `Copy` trait
}