Hi everybody, I am in the rocess of learning rust and I got confused about Vec (and the index trait in general I think); given the signature of Index: fn index(&self, index: Idx) -> &Self::Output;
my expectation was for it to give back a reference but the following code does not compile because v[0]
wants to copy the element:
struct NotCopiable {
val: u32,
}
fn main() {
let mut v = vec![];
v.push(NotCopiable{val: 1});
let x = v.get(0).unwrap();
println!("Value is {}", x.val);
let x = v[0];
println!("Value is {}", x.val);
}
I can fix it using &v[0]
but I was expecting v.get(0).unwrap();
and v[0]
to be equivalent... why is it not the case? Can you please shed some light on this behaviour?
Of course, I am missing something in the working of it...
Thanks in advance