indexing - 为什么索引 HashMap 不返回引用?

我正在编写以下测试代码。

fn test() {
    let mut m = HashMap::new();
    m.insert("aaa".to_string(), "bbb".to_string());

    let a = m["aaa"];   // error [E0507] cannot move out of index of `HashMap<String, String>`
    let a  = m.index("aaa");  // ok, the type of a is &String. I think The compile will add & to m;
    let a :&String = (&m).index("aaa");  // ok, the type of a is &String.
    println!("{:?}", m["aaa"]);  // ok
}

我不明白为什么m["aaa"]的返回类型是String,而不是&String。因为index(&self, key: &Q) -> &V特征 Index 有一个 &self 参数,我认为编译会添加一个 & 到 m,并且 m["aaa 的返回类型"] 应该是 &String,所以字符串 "bbb"不会被移出 m。

如果编译时没有给m加上&,就找不到index()方法,错误应该是m cannot be indexed by "bbb";

最佳答案

来自 the docs for Index :

container[index] is actually syntactic sugar for *container.index(index)

那么当你写 m["aaa"] 时会发生什么? ,编译器实际上是添加一个*取消引用 Index::index 返回的值,而当您调用 m.index ("aaa") 时, 你得到 &String直接引用。

正如@user4815162342 所指出的,程序员应该通过编写 &m["aaa"] 来明确他们的意图。或 m["aaa"].clone() .

此外println!("{:?}", m["aaa"]);工作是因为 println!宏确实添加了一个 &到它访问的所有值¹,以防止显示引起的意外移动,这抵消了 *由编译器添加。


(1) 这在 format_args! 的文档中有间接记录宏。

https://stackoverflow.com/questions/69342374/

相关文章:

ruby-on-rails - Rails 参数方法 : Why can it be accesse

visual-studio-code - 如何在VSC终端创建文件?

reactjs - 如何更改Chakra UI Toast组件的背景颜色?

assembly - 如果 x86 jmp 跳转到其他两个连续有效地址之间的地址会发生什么?

javascript - MongooseServerSelectionError:连接 ECONN

python - python解释器是否隐含地使用了中国余数定理?

python - Linux Mint Cinnamon 错误打开设置(没有名为 'PIL' 的模块

c++ - 创建一个线程安全的原子计数器

r - 从 R 中的数据帧列表中进行子集化

c++ - 嵌套 std::map 的单行查找