FromIterator Collects Into A Custom Counter
Implement FromIterator for a histogram type so collect builds it straight from any iterator, then verify the result against a hand-written fold.
Code
use std::collections::HashMap;
use std::hash::Hash;
// 直方图:collect 的目标类型
#[derive(Debug, Default, PartialEq)]
struct Counter<K: Eq + Hash> {
counts: HashMap<K, usize>,
}
impl<K: Eq + Hash> Counter<K> {
fn bump(&mut self, key: K) {
*self.counts.entry(key).or_insert(0) += 1;
}
}
// 实现 FromIterator 后,collect::<Counter<_>>() 可以直接消费任意迭代器
impl<K: Eq + Hash> FromIterator<K> for Counter<K> {
fn from_iter<I: IntoIterator<Item = K>>(items: I) -> Self {
let mut counter = Counter::default();
for item in items {
counter.bump(item);
}
counter
}
}
fn main() {
let log = ["GET", "POST", "GET", "DELETE", "GET", "POST"];
// 自定义集合作为 collect 的目标
let counter: Counter<&str> = log.iter().copied().collect();
println!("collect: {counter:?}");
// 等价的手写 fold,两种写法结果相等
let folded = log.iter().copied().fold(Counter::default(), |mut acc, key| {
acc.bump(key);
acc
});
println!("fold: {folded:?}");
println!("equal: {}", counter == folded);
}How the snippet works
Everything happens inside the functions bump, from_iter and main.
Repetition is confined to for item in items — the rest of the file is straight-line.
Applying it
The main signature reads fn bump(&mut self, key: K)
The demo output is labeled (collect:, fold:, equal:), so every printed line maps back to its originating operation.
Execute the file and main walks through bump, in that order.
Statements that matter
let folded = log.iter().copied().fold(Counter::default(), |mut acc, key| {
acc.bump(key);
acc
});
let counter: Counter<&str> = log.iter().copied().collect();
fn from_iter<I: IntoIterator<Item = K>>(items: I) -> Self {
let mut counter = Counter::default();
for item in items {
counter.bump(item);
}
counter
}
Interactive Tools for This Topic
FAQ
- What does FromIterator Collects Into A Custom Counter print when run?
- Run it as a complete program — the output lines carry labels such as `collect:`, `fold:`, `equal:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.