蓝色天空网mbsky.com · 知识 · 实践 · 创造Rust · 本地阅读预览
教程 / 后端开发 / Rust

Rust 集合与字符串

核对 Rust 标准库三大核心集合:动态数组 Vec<T>、UTF-8 编码字符串 String(字节长度、字符迭代与边界切片)以及散列映射表 HashMap<K, V>。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

向量 Vec<T> 的创建、追加、访问与遍历

集合(Collection)将数据存放在堆上以支持运行期动态伸缩。向量 `Vec<T>` 在内存中连续线性排列同类型元素,既可通过 `Vec::new()` 构造空向量,也可通过宏 `vec![1, 2, 4, 8]` 快速初始化。向尾部追加单个元素使用 `push`(如依次压入 `16`、`32`、`64`);合并另一向量全部元素使用 `v1.append(&mut v2)`,该操作会把 `v2` 的所有元素移入 `v1` 并将 `v2` 清空。

读取向量元素有两种方式:`v.get(idx)` 返回 `Option<&T>`,越界时安全返回 `None`;下标访问 `v[1]` 书写简洁,但越界(如访问 4 元素向量的 `v[4]`)会直接触发运行时 panic。遍历只读元素使用 `for i in &v`,若需在遍历中修改每个元素则使用 `for i in &mut v { *i += 50; }` 解引用写回。本站离线校验器核对了 `push`、`append` 排空源向量、`get(0)/get(4)`、越界异常与 `&mut` 原地加 50 得到 `[150, 82, 107]`。

String 字符串构造、拼接与 UTF-8 编码特性

`String` 内部以合法 UTF-8 字节向量存储,天然支持阿拉伯语、日语、韩语、中文、俄语等多语种文本。可通过 `String::new()`、`.to_string()`(适用于实现 `Display` 的数字、切片等)或 `String::from(...)` 构造;追加子串与单字符分别使用 `push_str(...)` 与 `push('!')`;用 `+` 拼接(`s1 + &s2` 或链式 `s1 + "-" + &s2 + "-" + &s3`)会消耗左侧 `String` 的所有权并借用右侧 `&str`,而 `format!("{}-{}-{}", s1, s2, s3)` 宏不会夺取任何参数所有权,组合多段文本更清晰。

由于 UTF-8 是变长编码(ASCII 占 1 字节,常见汉字占 3 字节),`"hello".len()` 返回字节数 `5`,而 `"你好".len()` 返回字节数 `6`;若需统计 Unicode 标量字符数,须调用 `"hello你好".chars().count()`(返回 `7`,需线性扫描故慢于 `O(1)` 的 `.len()`)。遍历字符应使用 `for c in s.chars()`;单次取第 `n` 个字符可用 `s.chars().nth(2)`(对 `"EN中文"` 返回 `Some('中')`),切忌在循环中反复调用 `nth` 以免退化为 `O(n^2)`。按字节切片 `&s[0..2]` 对 `"EN中文"` 合法得到 `"EN"`,但 `&s[0..3]` 切在 `'中'`(字节 `2..5`)中间会立即触发 `byte index 3 is not a char boundary` panic。离线校验器已逐一验证字节长度、字符计数与边界报错。

散列映射表 HashMap<K, V>

`std::collections::HashMap<K, V>` 用于存储键值对,调用 `HashMap::new()` 后编译器可由后续 `map.insert("color", "red")` 自动推导键值类型。最常用操作为 `insert` 写入、`get` 查询(返回 `Option<&V>`)以及 `map.iter()` 迭代 `(&K, &V)` 元组。`insert` 对已存在键会直接覆盖旧值;若希望“仅在键缺失时才插入”,应使用 `map.entry("color").or_insert("red")`;若确定键可能存在且需原地改写值,可用 `if let Some(x) = map.get_mut(&1) { *x = "b"; }`。离线校验器核对了 `insert`/`get`/`iter`、`entry().or_insert()` 不覆盖已有值及 `get_mut` 原地更新。

运行离线 Python 校验:Rust Vec<T>、UTF-8 String 边界切片与 HashMap Entry API

python · 阅读源码
"""Offline Rust semantic verifier for Chapter 24: Collections & String (Vec<T>, UTF-8 String, HashMap<K, V>)."""
import json


def utf8_slice(s: str, start: int, end: int) -> tuple[bool, str]:
    raw = s.encode("utf-8")
    def is_boundary(idx: int) -> bool:
        if idx == 0 or idx == len(raw):
            return True
        return 0 < idx < len(raw) and (raw[idx] & 0xC0) != 0x80

    if not (is_boundary(start) and is_boundary(end)):
        return False, f"byte index {end if not is_boundary(end) else start} is not a char boundary"
    return True, raw[start:end].decode("utf-8")


def run_cases() -> list[dict]:
    cases = []

    # Case 1: Vec<T> push, append (drains v2), get -> Option, indexing panic, &mut iteration
    v1 = [1, 2, 4, 8]
    for x in (16, 32, 64):
        v1.append(x)
    v_a = [1, 2, 4, 8]
    v_b = [16, 32, 64]
    v_a.extend(v_b)
    v_b.clear()  # Rust Vec::append moves all elements out of v2, leaving v2 empty

    v_get = [1, 2, 4, 8]
    get_0 = ("Some", v_get[0]) if 0 < len(v_get) else ("None", None)
    get_4 = ("Some", v_get[4]) if 4 < len(v_get) else ("None", None)
    idx_oob_panicked = False
    try:
        _ = v_get[4]
    except IndexError:
        idx_oob_panicked = True

    v_mut = [100, 32, 57]
    for idx in range(len(v_mut)):
        v_mut[idx] += 50

    actual_1 = {
        "after_push": v1,
        "after_append": v_a,
        "source_vec_drained": v_b == [],
        "get_0_and_4": [list(get_0), list(get_4)],
        "index_4_panics": idx_oob_panicked,
        "mut_iter_plus_50": v_mut,
    }
    expected_1 = {
        "after_push": [1, 2, 4, 8, 16, 32, 64],
        "after_append": [1, 2, 4, 8, 16, 32, 64],
        "source_vec_drained": True,
        "get_0_and_4": [["Some", 1], ["None", None]],
        "index_4_panics": True,
        "mut_iter_plus_50": [150, 82, 107],
    }
    cases.append(dict(
        name="vec_push_append_get_and_mut_iter",
        summary="Verify Vec push/append drain, Option-returning get(), OOB index panic, and &mut traversal",
        expected=expected_1,
        actual=actual_1,
        passed=actual_1 == expected_1,
    ))

    # Case 2: String construction, push_str/push, +, format!, UTF-8 byte len vs chars().count() & boundary panic
    s_push = "rust"
    s_push += "_lang"
    s_push += "!"
    s_plus = "Hello, " + "world!"
    s_fmt = f"{'tic'}-{'tac'}-{'toe'}"
    s_mix = "hello你好"
    s_cn = "EN中文"
    chars_list = list("hello中文")
    nth_2 = list(s_cn)[2]
    ok_sub, sub_val = utf8_slice(s_cn, 0, 2)
    bad_sub, bad_err = utf8_slice(s_cn, 0, 3)

    actual_2 = {
        "push_result": s_push,
        "plus_and_format": [s_plus, s_fmt],
        "byte_lens": [len("hello".encode("utf-8")), len("你好".encode("utf-8"))],
        "char_count_mix": len(s_mix),
        "chars_iter": chars_list,
        "nth_2": nth_2,
        "valid_slice_0_2": [ok_sub, sub_val],
        "invalid_slice_0_3": [bad_sub, "not a char boundary" in bad_err],
    }
    expected_2 = {
        "push_result": "rust_lang!",
        "plus_and_format": ["Hello, world!", "tic-tac-toe"],
        "byte_lens": [5, 6],
        "char_count_mix": 7,
        "chars_iter": ["h", "e", "l", "l", "o", "中", "文"],
        "nth_2": "中",
        "valid_slice_0_2": [True, "EN"],
        "invalid_slice_0_3": [False, True],
    }
    cases.append(dict(
        name="string_utf8_len_chars_and_slicing",
        summary="Verify String mutations, UTF-8 byte length (6 for 你好) vs char count (7), nth(2), and char-boundary panic",
        expected=expected_2,
        actual=actual_2,
        passed=actual_2 == expected_2,
    ))

    # Case 3: HashMap insert, get, iter, entry().or_insert(), and get_mut()
    hm: dict[str, str] = {}
    hm["color"] = "red"
    hm["size"] = "10 m^2"
    color_val = hm.get("color")
    pairs = sorted(hm.items())
    # entry("color").or_insert("blue") should NOT overwrite existing "red"
    hm.setdefault("color", "blue")
    hm.setdefault("theme", "sky")

    hm_int: dict[int, str] = {1: "a"}
    if 1 in hm_int:
        hm_int[1] = "b"

    actual_3 = {
        "get_color": color_val,
        "iter_pairs": [list(p) for p in pairs],
        "after_entry_or_insert": {"color": hm["color"], "theme": hm["theme"]},
        "after_get_mut": hm_int[1],
    }
    expected_3 = {
        "get_color": "red",
        "iter_pairs": [["color", "red"], ["size", "10 m^2"]],
        "after_entry_or_insert": {"color": "red", "theme": "sky"},
        "after_get_mut": "b",
    }
    cases.append(dict(
        name="hashmap_insert_entry_and_get_mut",
        summary="Verify HashMap insert/get/iter, non-overwriting entry().or_insert(), and get_mut() update",
        expected=expected_3,
        actual=actual_3,
        passed=actual_3 == expected_3,
    ))

    return cases


def main() -> None:
    payload = {
        "version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
        "cases": run_cases(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 Vec push/append 排空/get Option/&mut 遍历、你好字节长 6 与 chars 计数 7、EN中文 [0..3] 边界 panic 及 HashMap entry/get_mut。
运行离线 Python 校验:Rust Vec<T>、UTF-8 String 边界切片与 HashMap Entry API

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:146ae00ff2bd98e072121cdfa8f06917f63424c1188522c60fb0a35b5e82af22

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Rust 集合与字符串实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:b3a89d683860b0f2d1981a697b2336d978a6bcfc39dadb22ffba694ab162a7b0

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 Rust 中不能用 s[0] 直接索引 String,且在遍历中文字符串时不应在循环内反复调用 s.chars().nth(i)?

展开参考解答

String 底层是变长 UTF-8 字节序列,单字节既可能不是完整字符,扫描第 i 个字符也无法做到 O(1);循环内每次调用 s.chars().nth(i) 都会从头解码,整体时间复杂度会退化为 O(n^2),应直接用 for c in s.chars() 顺序迭代。

规范与官方依据