字典/键值对
1. Rust 中的 HashMap 内容
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
// 插入键值对
map.insert("apple", 3);
map.insert("banana", 2);
map.insert("orange", 5);
// 访问值
if let Some(&count) = map.get("apple") {
println!("苹果的数量: {}", count);
}
// 遍历键值对
for (key, value) in &map {
println!("{}: {}", key, value);
}
// 移除键值对
map.remove("banana");
}2. 与其他语言的 Map 比较
特性
Rust HashMap
Java Map
Python dict
C++ std::unordered_map
3. 总结
Last updated