有没有办法在 Rust 中使用 HashMap 并获取值向量?

问题描述 投票:0回答:2

我有一个

hashmap: HashMap<SomeKey, SomeValue>
,我想使用
hashmap
并将其所有值作为向量获取。

我现在的做法是

let v: Vec<SomeValue> = hashmap.values().cloned().collect();

cloned
复制每个值,但这种构造不会消耗哈希图。我可以接受使用地图。

有没有办法在不复制的情况下获取值?

rust hashmap
2个回答
14
投票

将整个

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<_>
中。

另请参阅:


0
投票

从 Rust 1.54 开始,你可以使用

HashMap::into_values
:

let v: Vec<_> = hashmap.into_values().collect();
© www.soinside.com 2019 - 2024. All rights reserved.