The compiler says that e1: &i32
and e2: i32
. Having read the docs for slice::Iter
and the book chapter on loops, I'm still confused.
More generally, can a particular element in a slice be owned? It seems like in case 2, e2
is owning an element, is it?
fn main() {
let slice = &[1, 2, 3];
for e1 in slice.iter() {
println!("{}", e1); // case 1
}
for &e2 in slice.iter() {
println!("{}", e2); // case 2
}
}
When used in a destructuring pattern binding, the ampersand
&
is used to dereference a value:This applies anywhere a pattern is accepted, such as in a
let
orif let
, as a function argument, the for-loop variable, or a match arm.While initially confusing to many people, this is actually the language being consistent with how enums and structs are pattern matched and thus removed from the inner variable binding:
Note how
val
is no longer "wrapped" by theSome
, just like it is no longer "wrapped" by the reference.This behavior of
&
in patterns is why theref
keyword is needed. Theref
keyword is used to unambiguously introduce a reference in a pattern match.