gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:21:54 25 4
gpt4 key购买 nike

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

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! 的文档中有间接记录宏。

关于indexing - 为什么索引 HashMap 不返回引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69342374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com