【问题标题】:Is there a way to consume a HashMap and get a vector of values in Rust?有没有办法使用 HashMap 并在 Rust 中获取值向量?
【发布时间】:2020-05-04 18:03:14
【问题描述】:

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

我现在的做法是

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

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

有什么方法可以在不复制的情况下获取值吗?

【问题讨论】:

    标签: rust hashmap


    【解决方案1】:

    将整个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&lt;_&gt;。

    另见:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 2020-04-16
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多