繁体   English   中英

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

[英]Why does indexing a HashMap not return a reference?

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

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 因为trait Indexindex(&self, key: &Q) -> &V有一个&self参数,我觉得编译会在m后面加一个& ,m["aaa"]的返回类型应该是&String,所以String “bbb”不会被移出 m。

如果编译不在m中添加&,将找不到index()方法,错误应该是m cannot be indexed by "bbb"

来自Index的文档

container[index]实际上是*container.index(index)的语法糖

因此,当您编写m["aaa"]时,编译器实际上添加了一个*以取消引用Index::index返回的值,而当您调用m.index ("aaa")时,您会得到&String直接参考。

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

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


(1) 这在format_args! 宏。

暂无
暂无

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

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