Learning-Rust.Github.io:面向所有人的 Rust 编程语言教程
Learning-Rust.Github.io: Rust Programming Language Tutorials for Everyone
原始链接: https://learning-rust.github.io
```rust
use std::collections::HashMap;
enum Data {
Value(V),
KeyValue(K, V),
}
fn main() {
let data = vec![
Data::KeyValue("Steve", 10),
Data::Value(20),
Data::KeyValue("Bill", 30),
Data::Value(40),
];
let map = data
.into_iter()
// 模式匹配与解构
.map(|item| match item {
Data::KeyValue(k, v) => {
println!("{k}: {v}");
(k.to_string(), v)
}
Data::Value(v) => {
println!("unknown: {v}");
("unknown".to_string(), v)
}
})
// 将项累加到 map 中
.fold(HashMap::new(), |mut map, (key, value)| {
map.entry(key)
.and_modify(|existing| *existing += value)
.or_insert(value);
map
});
println!("Map: {:?}", map); // Map: {"unknown": 60, "Bill": 30, "Steve": 10}
}
```