Skip to content

05 - 集合与字符串

标准库常用集合:Vec<T> / String / HashMap<K,V> / HashSet<T> / BTreeMap / VecDeque。

一、Vec<T> - 动态数组

1. 创建

fn main() {
    // Vec::new
    let mut v1: Vec<i32> = Vec::new();

    // vec! 宏
    let v2 = vec![1, 2, 3];

    // 指定容量(避免多次扩容)
    let mut v3: Vec<i32> = Vec::with_capacity(10);
    println!("cap: {}, len: {}", v3.capacity(), v3.len());
}

2. 添加 / 移除

fn main() {
    let mut v = vec![1, 2, 3];

    v.push(4);
    v.push(5);

    // 末尾移除
    let last = v.pop(); // Option<T>
    println!("{:?}", last); // Some(5)

    // 指定位置移除
    let second = v.remove(1);
    println!("{:?}", v); // [1, 3, 4]

    // 扩展
    v.extend([10, 20, 30]);
    v.extend_from_slice(&[100, 200]);

    // 插入
    v.insert(1, 99);
    println!("{:?}", v);

    // 保留 / 删除
    v.retain(|&x| x % 2 == 0);
    println!("{:?}", v);

    // 清空
    v.clear();
}

3. 访问

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    // 索引(越界 panic)
    println!("{}", v[2]);

    // get(越界 None)
    match v.get(2) {
        Some(x) => println!("get(2) = {}", x),
        None => println!("out of range"),
    }

    // first / last
    println!("{:?}", v.first()); // Some(1)
    println!("{:?}", v.last());  // Some(5)

    // contains
    println!("{}", v.contains(&3));
}

4. 遍历

fn main() {
    let mut v = vec![1, 2, 3];

    // 不可变引用
    for x in &v {
        println!("{}", x);
    }

    // 可变引用(修改)
    for x in &mut v {
        *x *= 2;
    }
    println!("{:?}", v); // [2, 4, 6]

    // 消耗所有权
    for x in v {
        println!("{}", x);
    }
    // v 已失效
}

5. 排序与去重

fn main() {
    let mut v = vec![3, 1, 4, 1, 5, 9, 2, 6];
    v.sort();
    println!("{:?}", v); // [1, 1, 2, 3, 4, 5, 6, 9]

    // 自定义排序
    v.sort_by(|a, b| b.cmp(a)); // 降序
    println!("{:?}", v);

    // 去重(需要先排序)
    v.dedup();
    println!("{:?}", v);

    // 反转
    v.reverse();
}

6. 其他常用

fn main() {
    let v = vec![1, 2, 3, 4, 5];

    // 长度与容量
    println!("len: {}, cap: {}", v.len(), v.capacity());

    // 拼接
    let v2 = vec![6, 7, 8];
    let v3 = v.into_iter().chain(v2).collect::<Vec<_>>();
    println!("{:?}", v3);

    // 切片
    let s: &[i32] = &v3[1..4];
    println!("{:?}", s);

    // 任意 T 类型(用宏)
    let mixed = vec![1, "two", 3.0]; // ❌ 编译错误,元素类型必须一致

    // 用枚举混合
    #[derive(Debug)]
    enum Cell { Int(i32), Float(f64), Text(String) }
    let mixed: Vec<Cell> = vec![
        Cell::Int(1),
        Cell::Float(2.0),
        Cell::Text("three".into()),
    ];
    println!("{:?}", mixed);
}

二、String - 字符串

1. 本质

  • String = Vec<u8> 包装,保证 UTF-8 有效
  • &str = &[u8] 视图,字符串字面量就是 &'static str

2. 创建

fn main() {
    let s1 = String::new();
    let s2 = String::from("hello");
    let s3 = "world".to_string();
    let s4: String = "rust".into();
    let s5 = "ABC".repeat(3); // ABCABCABC

    println!("{} {} {} {}", s2, s3, s4, s5);
}

3. 修改

fn main() {
    let mut s = String::from("hello");

    // push 单个字符
    s.push(' ');
    s.push('w');

    // push_str 字符串切片
    s.push_str("orld");

    // + 拼接(左侧 String 被 move)
    let s2 = String::from("!");
    let s3 = s + &s2; // s 被消费,s3 拥有结果

    // format! 拼接多个(不消费任何)
    let a = String::from("tic");
    let b = String::from("tac");
    let c = String::from("toe");
    let s4 = format!("{}-{}-{}", a, b, c);
    println!("{}", s4);
}

4. 访问

fn main() {
    let s = String::from("你好 Rust");

    // 字节长度(UTF-8 中中文 3 字节)
    println!("len: {}", s.len());        // 10

    // 字符数
    println!("chars: {}", s.chars().count()); // 6

    // 字节切片(必须落在 UTF-8 边界)
    // let sub = &s[0..2]; // ❌ 不是边界
    let sub = &s[0..3];    // "你"

    // 字符迭代
    for c in s.chars() {
        print!("{} ", c);
    }
    println!();

    // 字节迭代
    for b in s.bytes() {
        print!("{} ", b);
    }
    println!();
}

5. 常用方法

fn main() {
    let s = String::from("  Hello, World!  ");

    println!("trim: '{}'", s.trim());                  // "Hello, World!"
    println!("upper: '{}'", s.to_uppercase());
    println!("lower: '{}'", s.to_lowercase());

    println!("contains 'World': {}", s.contains("World"));
    println!("starts_with 'Hello': {}", s.trim_start_matches(' ').starts_with("Hello"));

    // 替换
    let s2 = s.replace("World", "Rust");

    // 拆分
    let csv = "a,b,c,d";
    let parts: Vec<&str> = csv.split(',').collect();
    println!("{:?}", parts);

    // 多次拆分
    let words: Vec<&str> = "hello world rust".split_whitespace().collect();

    // 行
    let multiline = "line1\nline2\nline3";
    let lines: Vec<&str> = multiline.lines().collect();

    // trim 系列
    let path = "///path///";
    let trimmed = path.trim_matches('/');
    println!("trim_matches: {}", trimmed); // path

    // parse
    let n: i32 = "42".parse().unwrap();
}

6. UTF-8 安全

fn main() {
    let s = String::from("नमस्ते"); // 印地语

    // 不能用下标直接访问
    // let c = s[0]; // ❌

    // 必须用 chars() / bytes()
    for c in s.chars() {
        print!("'{}' ", c);
    }
    println!();

    // 子串(必须落在 char 边界)
    // 找前 18 字节的位置
    let mut i = 0;
    for (idx, _) in s.char_indices() {
        if idx == 18 {
            i = idx;
            break;
        }
    }
    let sub = &s[..i];
    println!("{}", sub);
}

三、HashMap<K, V> - 哈希映射

1. 创建

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<String, i32> = HashMap::new();

    scores.insert(String::from("Alice"), 100);
    scores.insert(String::from("Bob"), 85);
    scores.insert(String::from("Charlie"), 92);

    // 用 collect 从 zip
    let teams = vec![String::from("Red"), String::from("Blue")];
    let initial = vec![10, 50];
    let scores2: HashMap<_, _> = teams.into_iter().zip(initial.into_iter()).collect();
    println!("{:?}", scores2);
}

2. 访问

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 100);

    // get -> Option<&V>
    match scores.get("Alice") {
        Some(v) => println!("Alice: {}", v),
        None => println!("not found"),
    }

    // 直接访问(panic)
    // println!("{}", scores["Alice"]);

    // 遍历
    for (k, v) in &scores {
        println!("{}: {}", k, v);
    }
}

3. 更新

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 100);

    // 覆盖
    scores.insert("Alice", 105);

    // 不存在才插入
    scores.entry("Bob").or_insert(80);

    // 基于旧值更新
    let count = scores.entry("Alice").or_insert(0);
    *count += 1;

    println!("{:?}", scores);
}

4. 词频统计实战

use std::collections::HashMap;

fn word_count(text: &str) -> HashMap<&str, i32> {
    let mut map = HashMap::new();
    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count += 1;
    }
    map
}

fn main() {
    let text = "hello world wonderful world hello rust hello";
    let counts = word_count(text);
    println!("{:?}", counts);
    // {"hello": 3, "world": 2, "wonderful": 1, "rust": 1}
}

5. 自定义键类型

use std::collections::HashMap;
use std::hash::{Hash, Hasher};

#[derive(Eq, PartialEq, Hash)]
struct Point { x: i32, y: i32 }

fn main() {
    let mut map: HashMap<Point, &'static str> = HashMap::new();
    map.insert(Point { x: 0, y: 0 }, "origin");
    map.insert(Point { x: 1, y: 1 }, "diagonal");

    println!("{:?}", map.get(&Point { x: 0, y: 0 }));
}

四、HashSet<T> - 集合

use std::collections::HashSet;

fn main() {
    let mut s: HashSet<i32> = HashSet::new();
    s.insert(1);
    s.insert(2);
    s.insert(2); // 重复,不插入
    println!("{:?}", s); // {1, 2}

    // 集合运算
    let a: HashSet<i32> = [1, 2, 3].into_iter().collect();
    let b: HashSet<i32> = [2, 3, 4].into_iter().collect();

    let union: HashSet<_> = a.union(&b).collect();
    let intersection: HashSet<_> = a.intersection(&b).collect();
    let difference: HashSet<_> = a.difference(&b).collect();

    println!("union: {:?}", union);          // {1, 2, 3, 4}
    println!("intersection: {:?}", intersection); // {2, 3}
    println!("difference: {:?}", difference); // {1}
}

五、其他常用集合

use std::collections::{BTreeMap, BTreeSet, VecDeque, LinkedList, BinaryHeap};

fn main() {
    // BTreeMap:有序 Map
    let mut bt = BTreeMap::new();
    bt.insert(3, "c");
    bt.insert(1, "a");
    bt.insert(2, "b");
    for (k, v) in &bt {
        println!("{}: {}", k, v); // 1:a 2:b 3:c (有序)
    }

    // BTreeSet:有序 Set
    let bs: BTreeSet<i32> = [3, 1, 2].into_iter().collect();

    // VecDeque:双端队列
    let mut dq: VecDeque<i32> = VecDeque::new();
    dq.push_back(1);
    dq.push_front(0);
    dq.push_back(2);

    println!("{:?}", dq); // [0, 1, 2]

    // BinaryHeap:最大堆
    let mut heap = BinaryHeap::new();
    heap.push(3);
    heap.push(1);
    heap.push(5);
    println!("{:?}", heap.pop()); // Some(5)
}

六、要点速记

  • Vec<T> 堆分配,可变长;[T; N] 栈分配,定长
  • String 是 UTF-8 字节序列,不能按下标访问
  • chars() 按字符迭代,bytes() 按字节迭代
  • 切片必须落在 UTF-8 字符边界,否则 panic
  • 字符串拼接优先 format!(不消费),+ 会消费左侧
  • HashMap 默认非确定性顺序,需要顺序用 BTreeMap
  • entry().or_insert() 是惯用的"插入或更新"模式
  • HashSet 是 HashMap<T, ()> 的薄包装
  • Vec::with_capacity 预设容量减少 realloc
  • sort 要求 Ord,sort_by 可自定义比较器

六、综合实战:日志分析器 (log_analyzer)

多文件项目,综合运用 Vec / String / HashMap / HashSet 处理真实日志数据。

1. 项目结构

log_analyzer/
├── Cargo.toml
├── samples/
│   └── access.log      # 示例输入
└── src/
    ├── main.rs         # CLI 入口
    ├── lib.rs          # 库入口
    ├── entry.rs        # 日志条目结构
    ├── parser.rs       # 日志行解析
    ├── stats.rs        # 统计分析
    └── report.rs       # 报告生成

2. Cargo.toml

[package]
name = "log_analyzer"
version = "0.1.0"
edition = "2021"

3. samples/access.log

192.168.1.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 1234
192.168.1.2 - - [10/Oct/2023:13:55:37 +0000] "GET /about HTTP/1.1" 200 5678
192.168.1.1 - - [10/Oct/2023:13:55:38 +0000] "POST /api/users HTTP/1.1" 201 89
192.168.1.3 - - [10/Oct/2023:13:55:39 +0000] "GET /missing HTTP/1.1" 404 0
192.168.1.1 - - [10/Oct/2023:13:55:40 +0000] "GET /index.html HTTP/1.1" 200 1234

4. src/entry.rs

use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct LogEntry {
    pub ip: String,
    pub method: String,
    pub path: String,
    pub status: u16,
    pub size: u64,
}

impl LogEntry {
    pub fn is_error(&self) -> bool {
        self.status >= 400
    }

    pub fn category(&self) -> &'static str {
        match self.status {
            100..=199 => "1xx",
            200..=299 => "2xx",
            300..=399 => "3xx",
            400..=499 => "4xx",
            500..=599 => "5xx",
            _ => "???",
        }
    }
}

/// 按 IP 聚合的统计
pub type IpStats = HashMap<String, IpStatsEntry>;

#[derive(Debug, Default, Clone)]
pub struct IpStatsEntry {
    pub count: u32,
    pub total_bytes: u64,
    pub errors: u32,
}

impl IpStatsEntry {
    pub fn record(&mut self, entry: &LogEntry) {
        self.count += 1;
        self.total_bytes += entry.size;
        if entry.is_error() {
            self.errors += 1;
        }
    }

    pub fn avg_size(&self) -> f64 {
        if self.count == 0 {
            0.0
        } else {
            self.total_bytes as f64 / self.count as f64
        }
    }
}

5. src/parser.rs

use crate::entry::LogEntry;

pub fn parse_line(line: &str) -> Option<LogEntry> {
    // 简化解析:ip method path status size
    let mut parts = line.split_whitespace();

    let ip = parts.next()?.to_string();

    // 跳过 "-" 和 "[...]"
    parts.next(); // -
    parts.next(); // [date:time]

    let request = parts.next()?;
    let mut req_parts = request.split_whitespace();
    let method = req_parts.next()?.trim_matches('"').to_string();
    let path = req_parts.next()?.trim_matches('"').to_string();

    let status: u16 = parts.next()?.parse().ok()?;
    let size: u64 = parts.next()?.parse().ok()?;

    Some(LogEntry { ip, method, path, status, size })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse() {
        let line = r#"192.168.1.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 1234"#;
        let e = parse_line(line).unwrap();
        assert_eq!(e.ip, "192.168.1.1");
        assert_eq!(e.method, "GET");
        assert_eq!(e.status, 200);
    }
}

6. src/stats.rs

use std::collections::{BTreeMap, HashMap, HashSet};

use crate::entry::{IpStats, IpStatsEntry, LogEntry};

pub fn top_ips(entries: &[LogEntry], n: usize) -> Vec<(String, u32)> {
    let mut counts: HashMap<String, u32> = HashMap::new();
    for e in entries {
        *counts.entry(e.ip.clone()).or_insert(0) += 1;
    }
    let mut v: Vec<_> = counts.into_iter().collect();
    v.sort_by(|a, b| b.1.cmp(&a.1));
    v.into_iter().take(n).collect()
}

pub fn status_distribution(entries: &[LogEntry]) -> BTreeMap<String, u32> {
    let mut dist = BTreeMap::new();
    for e in entries {
        *dist.entry(e.category().to_string()).or_insert(0) += 1;
    }
    dist
}

pub fn unique_paths(entries: &[LogEntry]) -> HashSet<String> {
    entries.iter().map(|e| e.path.clone()).collect()
}

pub fn ip_stats(entries: &[LogEntry]) -> IpStats {
    let mut stats: IpStats = HashMap::new();
    for e in entries {
        stats.entry(e.ip.clone()).or_default().record(e);
    }
    stats
}

pub fn error_rate(entries: &[LogEntry]) -> f64 {
    if entries.is_empty() {
        return 0.0;
    }
    let errors = entries.iter().filter(|e| e.is_error()).count();
    errors as f64 / entries.len() as f64
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample() -> Vec<LogEntry> {
        vec![
            LogEntry { ip: "1.1.1.1".into(), method: "GET".into(), path: "/".into(), status: 200, size: 100 },
            LogEntry { ip: "1.1.1.1".into(), method: "GET".into(), path: "/".into(), status: 200, size: 200 },
            LogEntry { ip: "2.2.2.2".into(), method: "POST".into(), path: "/api".into(), status: 404, size: 0 },
        ]
    }

    #[test]
    fn test_top_ips() {
        let top = top_ips(&sample(), 5);
        assert_eq!(top[0].0, "1.1.1.1");
        assert_eq!(top[0].1, 2);
    }

    #[test]
    fn test_error_rate() {
        assert!((error_rate(&sample()) - 1.0 / 3.0).abs() < 0.01);
    }
}

7. src/report.rs

use std::collections::BTreeMap;

use crate::entry::LogEntry;

pub fn generate_report(entries: &[LogEntry]) -> String {
    use crate::stats::*;

    let mut out = String::new();
    out.push_str("=== 日志分析报告 ===\n\n");

    out.push_str(&format!("总请求数: {}\n", entries.len()));
    out.push_str(&format!("错误率:   {:.2}%\n\n", error_rate(entries) * 100.0));

    out.push_str("--- Top 10 IP ---\n");
    for (ip, count) in top_ips(entries, 10) {
        out.push_str(&format!("  {}: {}\n", ip, count));
    }
    out.push('\n');

    out.push_str("--- 状态码分布 ---\n");
    for (cat, count) in status_distribution(entries) {
        out.push_str(&format!("  {}: {}\n", cat, count));
    }
    out.push('\n');

    out.push_str(&format!("--- 独立路径数: {} ---\n", unique_paths(entries).len()));

    out
}

#[allow(dead_code)]
fn _unused() -> BTreeMap<(), ()> { BTreeMap::new() }

8. src/lib.rs

pub mod entry;
pub mod parser;
pub mod report;
pub mod stats;

pub use entry::{IpStats, IpStatsEntry, LogEntry};
pub use parser::parse_line;
pub use report::generate_report;

9. src/main.rs

use std::env;
use std::fs;
use std::process;

use log_analyzer::{generate_report, parse_line};

fn main() {
    let path = env::args().nth(1).unwrap_or_else(|| "samples/access.log".into());

    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("无法读取 {}: {}", path, e);
            process::exit(1);
        }
    };

    let entries: Vec<_> = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(parse_line)
        .collect();

    println!("解析到 {} 条日志", entries.len());
    print!("{}", generate_report(&entries));
}

10. 运行

cargo run -- samples/access.log
# 解析到 5 条日志
# === 日志分析报告 ===
#
# 总请求数: 5
# 错误率:   20.00%
#
# --- Top 10 IP ---
#   192.168.1.1: 3
#   192.168.1.2: 1
#   192.168.1.3: 1
#
# --- 状态码分布 ---
#   2xx: 4
#   4xx: 1

11. 关键点

集合 用法
Vec<LogEntry> 主数据存储
HashMap<String, u32> IP 计数
BTreeMap<String, u32> 状态码分布(有序)
HashSet<String> 独立路径去重
HashMap::entry().or_default() 懒插入 + 累加
iter().filter_map() 解析失败跳过
BTreeMap 默认有序 报告输出按 1xx/2xx/... 排序