Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

rust

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.

like image 455
StrausMG Avatar asked Sep 12 '25 13:09

StrausMG


1 Answers

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)."

like image 146
John Kugelman Avatar answered Sep 15 '25 01:09

John Kugelman