This is a bit of helpful ergonomics that the compiler does for you in order to make the code look a bit nicer.
The return value of the Index
trait is a reference, but the compiler automatically inserts a dereference for you when you use the sugared syntax []
. Most other languages would just return the item from the array (copying it or returning another reference to the object, whatever is appropriate).
Due to Rust’s importance of move / copy semantics, you can’t always make a copy a value, so in those cases, you will usually use a &
:
let items = &[1u8, 2, 3, 4];
let a: u8 = items[0];
let a: u8 = *items.index(&0); // Equivalent of above
let b: &u8 = &items[0];
let b: &u8 = &*items.index(&0); // Equivalent of above
Note that the indexing value is also automatically taken by reference, similar to the automatic dereference.