集合类型 #
一、Vec 动态数组 #
1.1 创建 #
rust
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(1);
let v2 = vec![1, 2, 3, 4, 5];
let v3 = Vec::with_capacity(10);
println!("{:?}", v);
println!("{:?}", v2);
}
1.2 常用操作 #
rust
fn main() {
let mut v = vec![1, 2, 3];
v.push(4);
v.insert(0, 0);
v.pop();
v.remove(0);
println!("{:?}", v);
println!("长度: {}", v.len());
println!("容量: {}", v.capacity());
}
二、HashMap #
2.1 创建 #
rust
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert(String::from("one"), 1);
map.insert(String::from("two"), 2);
println!("{:?}", map);
// 从数组创建
let map2: HashMap<&str, i32> = [
("one", 1),
("two", 2),
].iter().cloned().collect();
println!("{:?}", map2);
}
2.2 访问 #
rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("one", 1);
map.insert("two", 2);
// get
if let Some(&value) = map.get("one") {
println!("one = {}", value);
}
// 遍历
for (key, value) in &map {
println!("{}: {}", key, value);
}
}
2.3 更新 #
rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("count", 1);
// 覆盖
map.insert("count", 2);
// 仅在键不存在时插入
map.entry("count").or_insert(3);
// 使用旧值
map.entry("count").and_modify(|v| *v += 1);
println!("{:?}", map);
}
三、HashSet #
3.1 创建 #
rust
use std::collections::HashSet;
fn main() {
let mut set: HashSet<i32> = HashSet::new();
set.insert(1);
set.insert(2);
set.insert(3);
println!("{:?}", set);
let set2: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
println!("{:?}", set2);
}
3.2 操作 #
rust
use std::collections::HashSet;
fn main() {
let mut set = HashSet::new();
set.insert(1);
set.insert(2);
// 检查存在
println!("包含 1: {}", set.contains(&1));
// 删除
set.remove(&1);
// 遍历
for x in &set {
println!("{}", x);
}
}
3.3 集合运算 #
rust
use std::collections::HashSet;
fn main() {
let a: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<i32> = [2, 3, 4].iter().cloned().collect();
// 并集
let union: HashSet<i32> = a.union(&b).cloned().collect();
println!("并集: {:?}", union);
// 交集
let intersection: HashSet<i32> = a.intersection(&b).cloned().collect();
println!("交集: {:?}", intersection);
// 差集
let difference: HashSet<i32> = a.difference(&b).cloned().collect();
println!("差集: {:?}", difference);
}
四、实践示例 #
4.1 单词统计 #
rust
use std::collections::HashMap;
fn word_count(text: &str) -> HashMap<&str, usize> {
let mut map = HashMap::new();
for word in text.split_whitespace() {
*map.entry(word).or_insert(0) += 1;
}
map
}
fn main() {
let text = "hello world hello rust world world";
let counts = word_count(text);
for (word, count) in counts {
println!("{}: {}", word, count);
}
}
4.2 缓存 #
rust
use std::collections::HashMap;
struct Cache<K, V> {
data: HashMap<K, V>,
}
impl<K: std::hash::Hash + Eq + Clone, V: Clone> Cache<K, V> {
fn new() -> Self {
Cache {
data: HashMap::new(),
}
}
fn get(&self, key: &K) -> Option<&V> {
self.data.get(key)
}
fn set(&mut self, key: K, value: V) {
self.data.insert(key, value);
}
}
fn main() {
let mut cache = Cache::new();
cache.set("key1", "value1");
if let Some(value) = cache.get(&"key1") {
println!("缓存值: {}", value);
}
}
五、总结 #
本章学习了:
- Vec 动态数组
- HashMap 键值对映射
- HashSet 集合
- 集合运算
下一章,我们将学习模块系统。
最后更新:2026-03-27