Home > Back-end >  Does this function auto-dereference a vector?
Does this function auto-dereference a vector?

Time:05-11

I am wondering why list[0] and number_list[0] have the same address.

To my understanding, we passed in a reference to number_list in for_question4, so list supposed to be a reference of number_list. When we called list[0] in for_question4, it is supposed to be the same as &number_list[0].

But when I print the address, list[0] and number_list[0] are on the same address. &list[0] and &number_list[0] are on the same address.

Does function auto-dereference the vector passed in to it? Is auto-dereference a thing in Rust? If so, in what condition would it do that?

fn for_question4(list: &[&str]) {
    println!("call index without reference {:p}", list[0]); // 0x103d23d5d

    println!("call index with reference {:p}", &list[0]); // 0x7fea9c405de0
}

fn main() {
    let number_list = vec!["1", "2", "3"];
    let result = for_question4(&number_list);

    println!("call index without reference {:p}", number_list[0]); // 0x103d23d5d
    println!("call index with reference {:p}", &number_list[0]); // 0x7fea9c405de0
    println!("call index with two reference {:p}", &&number_list[0]); // 0x7ffeebf46f80
}

CodePudding user response:

The [] operator is evaluated before the & operator. The [] operator auto-dereferences.

Here are some examples:

fn main() {
    let n = vec!["1", "2", "3"];

    println!("      n[0]  {:p}", n[0]);
    println!("   (&n)[0]  {:p}", (&n)[0]);
    println!("  (&&n)[0]  {:p}", (&&n)[0]);
    println!("     &n[0]  {:p}", &n[0]);
    println!("    &(n[0]) {:p}", &(n[0]));
    println!(" &((&n)[0]) {:p}", &((&n)[0]));
    println!("&((&&n)[0]) {:p}", &((&&n)[0]));
}
      n[0]  0x5597b8ccf002
   (&n)[0]  0x5597b8ccf002
  (&&n)[0]  0x5597b8ccf002
     &n[0]  0x5597b9f3fad0
    &(n[0]) 0x5597b9f3fad0
 &((&n)[0]) 0x5597b9f3fad0
&((&&n)[0]) 0x5597b9f3fad0

CodePudding user response:

Just figured it out thanks to @Finomnis

It was index operator ([]) that did the auto-dereference. According to reference:

For other types an index expression a[b] is equivalent to *std::ops::Index::index(&a, b), or *std::ops::IndexMut::index_mut(&mut a, b) in a mutable place expression context. Just as with methods, Rust will also insert dereference operations on a repeatedly to find an implementation.

  • Related