Rust learning: lessons, notes, and exercise crates

This commit is contained in:
2026-09-06 23:59:08 +07:00
commit 6ddf41aa81
119 changed files with 10873 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
use std::{collections::HashMap, hash::Hash};
pub fn tally<T, K, F>(items: &[T], key: F) -> HashMap<K, usize>
where
K: Eq + Hash,
F: Fn(&T) -> K,
{
let mut counts = HashMap::new();
for item in items {
*counts.entry(key(item)).or_insert(0) += 1;
}
counts
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn owned_key() {
let words = ["apple", "avocado", "banana"];
let counts = tally(&words, |w| w.chars().next().unwrap().to_string());
assert_eq!(counts.get("a"), Some(&2), "keys: {:?}", counts);
assert_eq!(counts.len(), 2, "keys: {:?}", counts);
}
}