您可能需要该HashMap::remove
方法- 它从地图中删除键并返回原始值而不是引用:
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);
};
}
Run Code Online (Sandbox Code Playgroud)
该get
方法必须返回对象的引用,因为原来的对象可以只在一个地方存在(它是由拥有HashMap
)。该remove
方法只能返回原始对象(即“取得所有权”),因为它从其原始所有者中删除了它。
根据具体情况,另一种解决方案可能是获取引用,调用.clone()
它来制作对象的新副本(在这种情况下,它不起作用,因为Clone
没有为我们的Thing
示例对象实现 - 但它会起作用如果值的方式,比方说,a 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);
}
}
Run Code Online (Sandbox Code Playgroud)
获取给定键的值有两种基本方法:get()
和get_mut()
。如果您只想读取值,请使用第一个,如果需要修改值,请使用第二个:
fn get(&self, k: &Q) -> Option<&V>
fn get_mut(&mut self, k: &Q) -> Option<&mut V>
Run Code Online (Sandbox Code Playgroud)
从它们的签名中可以看出,这两个方法都返回Option
而不是直接值。原因是可能没有与给定键关联的值:
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a")); // key exists
assert_eq!(map.get(&2), None); // key does not exist
Run Code Online (Sandbox Code Playgroud)
如果您确定映射包含给定的键,则可以使用unwrap()
从选项中获取值:
assert_eq!(map.get(&1).unwrap(), &"a");
Run Code Online (Sandbox Code Playgroud)
然而,一般来说,最好(也更安全)也考虑密钥可能不存在的情况。例如,您可以使用模式匹配:
if let Some(value) = map.get(&1) {
assert_eq!(value, &"a");
} else {
// There is no value associated to the given key.
}
Run Code Online (Sandbox Code Playgroud)