[英]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
索引, Output
为T
。 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.