此函数是否自动取消引用向量?

Does this function auto-dereference a vector?

我想知道为什么 list[0]number_list[0] 有相同的地址。

据我了解,我们在 for_question4 中传递了对 number_list 的引用,因此列表应该是对 number_list 的引用。当我们在for_question4中调用list[0]时,它应该与&number_list[0].

相同

但是当我打印地址时,list[0]number_list[0] 在同一个地址上。 &list[0]&number_list[0] 在同一个地址。

函数是否自动解引用传递给它的向量?自动取消引用是 Rust 中的一件事吗?如果是这样,它会在什么条件下这样做?

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
}

[] 运算符在& 运算符之前 被计算。 [] 运算符 auto-dereferences.

这里有一些例子:

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

感谢@Finomnis

刚刚弄明白了

索引运算符 ([]) 执行了 auto-dereference。根据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.