您可能想要HashMap::remove method - 它从映射中删除键并返回原始值而不是引用:
use std::collections::HashMap;
struct Thing {
content: String,
}
fn main() {
let mut hm: HashMap<u32, Thing> = HashMap::new();
hm.insert(
123,
Thing {
content: "abc".into(),
},
);
hm.insert(
432,
Thing {
content: "def".into(),
},
);
// Remove object from map, and take ownership of it
let value = hm.remove(&432);
if let Some(v) = value {
println!("Took ownership of Thing with content {:?}", v.content);
};
}
get 方法必须返回对对象的引用,因为原始对象只能存在于一个地方(它归HashMap 所有)。 remove 方法只能返回原始对象(即“取得所有权”),因为它将原始对象从其原始所有者那里移除。
另一种解决方案,视具体情况而定,可能是取引用,在其上调用.clone()以制作对象的新副本(在这种情况下它不起作用,因为Clone没有实现对于我们的 Thing 示例对象 - 但如果值方式,例如 String),它会起作用
最后值得注意的是,在许多情况下您仍然可以使用对对象的引用 - 例如,前面的示例可以通过获取引用来完成:
use std::collections::HashMap;
struct Thing {
content: String,
}
fn main() {
let mut hm: HashMap<u32, Thing> = HashMap::new();
hm.insert(
123,
Thing {
content: "abc".into(),
},
);
hm.insert(
432,
Thing {
content: "def".into(),
},
);
let value = hm.get(&432); // Get reference to the Thing containing "def" instead of removing it from the map and taking ownership
// Print the `content` as in previous example.
if let Some(v) = value {
println!("Showing content of referenced Thing: {:?}", v.content);
}
}