簡體   English   中英

如何使用 Rust 中的謂詞計算 HashMap 值?

[英]How to count HashMap values using a predicate in Rust?

我正在嘗試這個,但不起作用:

let map = HashMap::new();
map.insert(1, "aaa");
map.insert(2, "bbb");
let a = map.counts_by(|k, v| v.starts_with("a"));

什么是正確的方法?

Anything that iterates over collections in Rust is going to factor through the Iterator API, and unlike in Java where iterators are often implicitly used, it's very common in Rust to explicitly ask for an iterator (with .iter() ) and do some work directly在它的功能風格。 在您的情況下,我們需要在這里做三件事。

  1. 獲取HashMap的值。 這可以通過values方法完成,該方法返回一個迭代器。
  2. 只保留滿足特定謂詞的那些。 這是一個filter操作,將產生另一個迭代器。 請注意,這還沒有遍歷 hash map; 它只是產生另一個能夠在以后這樣做的迭代器。
  3. 使用count匹配項。

綜上所述,我們有

map.values().filter(|v| v.starts_with("a")).count()

您應該過濾HashMap的迭代器,然后計算迭代器的元素:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "aaa");
    map.insert(2, "bbb");

    assert_eq!(
        map.iter().filter(|(_k, v)| v.starts_with("a")).count(),
        1
    );
}

請注意,map 也必須標記為mut才能插入新元素,並且filter閉包解構為包含鍵和值的元組,而不是接受兩個單獨的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM