I just started learning rust and I am confused about how the ampersand placement affects the program in the following examples. I understand that ‘&’ indicates a reference to a variable, but I’m not sure how these examples differ.
Example 1, no ampersand:
let arr = [1,2,3];
for n in arr {
println!("number {}", n);
}
Example 2, on the array definition:
let arr = &[1,2,3];
for n in arr {
println!("number {}", n);
}
Example 3, in the for loop:
let arr = [1,2,3];
for n in &arr {
println!("number {}", n);
}
All three of these examples produce the same output:
number 1
number 2
number 3
Is there any difference in how this code executes, or in its efficiency or memory consumption?
Nack is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.