小编Joe*_*oey的帖子

为什么对 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
}
Run Code Online (Sandbox Code Playgroud)

m["aaa"]我不明白为什么is的返回类型String, not &String。因为trait的index(&self, key: &Q) -> &VIndex有一个&self …

indexing hashmap rust

3
推荐指数
1
解决办法
799
查看次数

标签 统计

hashmap ×1

indexing ×1

rust ×1