What is the type of Vec::<i32>[0]

Documents tell me vector can be indexed because it has implemented Index trait;
But there is something I confused, like the code following:

use std::ops::Index;

fn main() {
    let mut v = Vec::with_capacity(10);
    v.push(0);
    
    // can't compare `{integer}` with `&{integer}`
    // assert_eq!(v[0], Index::index(&v, 0));
    
    let v0 = unsafe { &*(&v[0] as *const _) }; 
    v[0] = 9;

    let _val = *v0;
    println!("{}", _val);
}
  1. v[0] is a type of integer, but call the index directly returns a type of &integer
  2. Then v[0] is a integer, OK, it maybe a temp variable.

But the output of println is 9, means v[0] is not passed by value, it is not a integer.
It seems to me &v[0] is a special syntax that can't been split into & and v[0]

Is here some magic?

Yes, indexing expressions that use the trait...

    vec[0]

...dereference the return from the trait.

    *<Vec<_> as Index<usize>>::index(&vec, 0)
//  ^

(Or the IndexMut equivalent.)[1]

https://doc.rust-lang.org/nightly/reference/expressions/array-expr.html#array-and-slice-indexing-expressions


  1. Code sample off the top of my head, not checked, but you get the idea. ↩︎

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.