简体   繁体   English

为什么索引 Vec 会返回一个值而不是 Index 所承诺的引用?

[英]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 ): Index trait 的文档说.index()方法返回对Output关联类型(链接)的引用:

fn index(&self, index: Idx) -> &Self::Output;

For Vec<T> and the usize index, Output is T .对于Vec<T>usize索引, OutputT So, I expect the variable a in the following snippet to have the type &i32 .因此,我希望以下代码段中的变量a具有&i32类型。

let v = vec![0];
let a = v[0];

However, the type of a is i32 .但是, a的类型是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.我正在学习 Rust,据我了解,Rust 要求您在任何地方都明确表示,并且从不隐式执行value<->reference转换。 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) ." std::ops::Index文档说,“ container[index]实际上是*container.index(index)的语法糖。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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