Vec index operator documentation

#1

It seems I don’t know how to read Rust’s documentation. I tried to write code like this:

let v = vec![String::from("one"), String::from("two")];
let first = v[0];

This doesn’t compile because let first = v[0] tries to move the String out of v. So I was looking at the Vec documentation but all I can find is a mention of the Index trait, which has this method:

fn index(&self, index: Idx) -> &Self::Output

So it returns a reference. But what is it that’s being referenced here and how can this possibly result in an attempt move anything?

I know that I can access the Vec element as &v[0] to avoid a move. But why do I have to do that given what the documentation says?

#2

&v[0] is syntax sugar for v.index(0) and v[0] is syntax sugar for *v.index(0).

It’s just how it’s defined, there isn’t much more to it.

2 Likes
#4

Ah I see, so this is a language thing and that’s why it’s not in the library docs. It makes sense because if it was actually a reference it would be inconsistent with how array indexing works.

Thanks for that!

#5

The reason they did it like this is because every other language does the same, for example in C, writing arr[i] on an int array returns an int, not a pointer to an int.

1 Like