StrausMG
StrausMG

Reputation: 395

Why does indexing a Vec return a value instead of a reference as promised by the Index?

The documentation for the Index trait says that the .index() method returns a reference to the Output associated type (link):

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

For Vec<T> and the usize index, Output is T. So, I expect the variable a in the following snippet to have the type &i32.

let v = vec![0];
let a = v[0];

However, the type of a is i32. Why? I am learning Rust and, as far as I understand, Rust requires you to be explicit everywhere and never performs value<->reference conversions implicitly. Hence the question.

Upvotes: 24

Views: 2590

Answers (1)

John Kugelman
John Kugelman

Reputation: 362157

There's an automatic dereference added when the brackets are de-sugared. The std::ops::Index documentation says, "container[index] is actually syntactic sugar for *container.index(index)."

Upvotes: 29

Related Questions