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