Learning rust, confused about Vec and the Index trait

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

1 Like

The arr[idx] syntax is designed to dereference the reference returned by index because that usually makes more sense.

v[0] is expanded to *v.index(0) (or *v.index_mut(0), depending on the context). This is done so that you can set the value with v[0] = value or copy it with value = v[0] without extra dereferencing.

2 Likes

Thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.