我有一个
hashmap: HashMap<SomeKey, SomeValue>
,我想使用 hashmap
并将其所有值作为向量获取。
我现在的做法是
let v: Vec<SomeValue> = hashmap.values().cloned().collect();
cloned
复制每个值,但这种构造不会消耗哈希图。我可以接受使用地图。
有没有办法在不复制的情况下获取值?
将整个
HashMap
转换为迭代器并丢弃键:
use std::collections::HashMap;
fn only_values<K, V>(map: HashMap<K, V>) -> impl Iterator<Item = V> {
map.into_iter().map(|(_k, v)| v)
}
然后您可以使用迭代器做任何您想做的事情,包括将其收集到
Vec<_>
中。
另请参阅: