我正在编写以下测试代码。
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 …