简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM