For example, are these the same, or does doing let x = myar[2]
clone the number 3 and put it in x
?
let myar = [1, 2, 3, 4, 5];
let x = myar[2];
let x = &myar[2];
For example, are these the same, or does doing let x = myar[2]
clone the number 3 and put it in x
?
let myar = [1, 2, 3, 4, 5];
let x = myar[2];
let x = &myar[2];
No.
let x = myar[2];
does indeed copy the value 3
and store it in x
, while let x = &myar[2];
stores a reference to the value 3
in myar
.
Note that the only reason let x = myar[2];
works at all is because i32
implements the Copy
trait. If we had an array storing a type that does not implement the Copy
trait, you wouldn't be able to do that at all. For example:
struct Number {
num: i32,
}
impl Number {
fn new(num: i32) -> Number {
Number { num }
}
}
// Note that Number does not implement the Copy trait
fn main() {
let number_list = [Number::new(1), Number::new(2), Number::new(3)];
// This does not work:
let _x = number_list[1];
// This does work:
let _x = &number_list[1];
}