Rust 结构体
核对 Rust 命名结构体定义、字段初始化简写、结构体更新语法与部分移动、元组结构体与单元结构体、Debug 调试输出,以及 impl 方法与关联函数。
学完这一章,你能够
- 核对 Rust 命名结构体定义、字段初始化简写、结构体更新语法与部分移动、元组结构体与单元结构体、Debug 调试输出,以及 impl 方法与关联函数。
命名结构体定义、实例化与更新语法
结构体(Struct)与元组都能组合多个不同类型的值,但结构体为类型本身及每个成员(字段)赋予明确名称,访问字段时无需记忆位置下标。使用 `struct Site { domain: String, name: String, nation: String, found: u32 }` 定义结构体时,仅声明类型而不创建实例,字段间以逗号分隔,大括号结尾不加分号。
实例化结构体采用 `结构体名 { 字段名: 字段值, ... }` 的键值形式,字段顺序不必与定义一致(字段名须与定义严格匹配,如 `found: 2013`)。当局部同名变量与字段一致时,可写成字段初始化简写(如 `domain, name,`)。若新实例的大部分字段沿用已有实例,可使用结构体更新语法 `..base`(`..base` 须置尾且后不加逗号);需注意未被覆盖的非 `Copy` 字段(如 `nation: String`)所有权会从原实例移出。本站离线校验器核对 `Site` 初始化、字段简写及 `..base` 更新后 `nation` 被部分移动而 `found`(`u32`)仍可复制的语义。
元组结构体、单元结构体与结构体所有权
元组结构体形如 `struct Color(u8, u8, u8);` 与 `struct Point(f64, f64);`,兼具具名独立类型与元组下标访问(`.0`、`.1`、`.2`)的简洁性,适合颜色、二维坐标等高频简单载体;即便字段类型列表相同,不同元组结构体仍属于互不兼容的独立类型。
结构体实例通常拥有其字段的所有权(因此示例多采用 `String` 而非 `&str`),实例离开作用域时会自动按序释放各字段;若确需在结构体内存放引用字段,必须配合生命周期参数标注(见生命周期章节)。此外,不含任何字段的 `struct UnitStruct;` 称为单元结构体(Unit Struct),常作为零大小标记类型或在无状态类型上实现特性。离线校验器已验证 `Color(0, 0, 0)`、`Point(0.0, 0.0)` 下标访问、名义类型区分及零大小单元结构体。
Debug 调试格式化、方法与关联函数
为便于调试打印整块结构体内容,可在类型定义前添加 `#[derive(Debug)]` 派生调试特性,随后在 `println!` 中以 `{:?}` 单行输出 `Rectangle { width: 30, height: 50 }`,字段较多时改用 `{:#?}` 进行多行缩进美化输出。
结构体方法定义在 `impl Rectangle { ... }` 块中,首参通常为 `&self`(借用只读)、`&mut self`(可变借用)或 `self`(获取所有权),其中 `self` 为关键字无需手写类型;调用如 `rect1.area()` 或 `rect1.wider(&rect2)` 时由编译器自动传入接收者。以 `Rectangle { width: 30, height: 50 }` 与 `Rectangle { width: 40, height: 20 }` 为例,前者面积为 `1500`,调用 `rect1.wider(&rect2)` 返回 `false`。
在 `impl` 块中不接收 `self` 参数的函数称为关联函数(Associated Function),常用于构造器(例如 `String::from` 或 `Rectangle::create(width, height)`),通过 `类型名::函数名` 调用。同一结构体允许编写多个 `impl` 块,编译器会将其成员合并。离线校验器已核对 `{:?}`/`{:#?}` 格式化、`area()`、`wider()` 与 `Rectangle::create(30, 50)` 的全部结果。
运行离线 Python 校验:Rust 结构体更新部分移动、元组/单元结构体、Debug 输出与 impl 方法
"""Offline Rust semantic verifier for Chapter 17: Struct (definition, update syntax, tuple/unit structs, impl)."""
from dataclasses import dataclass
import json
@dataclass
class Site:
domain: str
name: str
nation: str
found: int
def update_from(self, **overrides) -> tuple["Site", list[str]]:
"""Models Rust `Site { field: val, ..base }` moving non-Copy String fields not overridden."""
moved_fields = []
values = {}
for field_name, is_copy in (("domain", False), ("name", False), ("nation", False), ("found", True)):
if field_name in overrides:
values[field_name] = overrides[field_name]
else:
values[field_name] = getattr(self, field_name)
if not is_copy:
moved_fields.append(field_name)
return Site(**values), moved_fields
@dataclass(frozen=True)
class Color:
r: int
g: int
b: int
def __getitem__(self, idx: int) -> int:
return (self.r, self.g, self.b)[idx]
@dataclass(frozen=True)
class Point:
x: float
y: float
def __getitem__(self, idx: int) -> float:
return (self.x, self.y)[idx]
@dataclass
class Rectangle:
width: int
height: int
# impl Rectangle (block 1)
def area(self) -> int:
return self.width * self.height
def wider(self, other: "Rectangle") -> bool:
return self.width > other.width
# impl Rectangle (block 2 - associated function)
@classmethod
def create(cls, width: int, height: int) -> "Rectangle":
return cls(width=width, height=height)
def debug_compact(self) -> str:
return f"Rectangle {{ width: {self.width}, height: {self.height} }}"
def debug_pretty(self) -> str:
return f"Rectangle {{\n width: {self.width},\n height: {self.height},\n}}"
class UnitStruct:
__slots__ = ()
def size_bytes(self) -> int:
return 0
def run_cases() -> list[dict]:
cases = []
# Case 1: Named struct init, field shorthand, and struct update syntax
domain = "www.example.org"
name = "MBSKY"
base = Site(domain=domain, name=name, nation="China", found=2024)
updated, moved = base.update_from(domain="docs.example.org", name="DOCS")
actual_1 = {
"base_found": base.found,
"updated": [updated.domain, updated.name, updated.nation, updated.found],
"moved_non_copy_fields": moved,
}
expected_1 = {
"base_found": 2024,
"updated": ["docs.example.org", "DOCS", "China", 2024],
"moved_non_copy_fields": ["nation"],
}
cases.append(dict(
name="struct_init_shorthand_and_update",
summary="Verify named struct initialization, field shorthand, and ..base partial move semantics",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Tuple structs and Unit struct
black = Color(0, 0, 0)
origin = Point(0.0, 0.0)
unit = UnitStruct()
actual_2 = {
"black": f"black = ({black[0]}, {black[1]}, {black[2]})",
"origin": f"origin = ({origin[0]:.0f}, {origin[1]:.0f})",
"distinct_types": type(black).__name__ != type(origin).__name__,
"unit_size": unit.size_bytes(),
}
expected_2 = {
"black": "black = (0, 0, 0)",
"origin": "origin = (0, 0)",
"distinct_types": True,
"unit_size": 0,
}
cases.append(dict(
name="tuple_struct_and_unit_struct",
summary="Verify tuple struct indexed access, nominal type distinction, and zero-sized unit struct",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Debug formatting ({:?} and {:#?})
rect1 = Rectangle(width=30, height=50)
actual_3 = {
"compact": f"rect1 is {rect1.debug_compact()}",
"pretty_lines": rect1.debug_pretty().splitlines(),
}
expected_3 = {
"compact": "rect1 is Rectangle { width: 30, height: 50 }",
"pretty_lines": ["Rectangle {", " width: 30,", " height: 50,", "}"],
}
cases.append(dict(
name="struct_debug_formatting",
summary="Verify #[derive(Debug)] {:?} compact and {:#?} pretty output for Rectangle",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
# Case 4: Struct methods (&self, multi-param) and associated function (::create)
rect2 = Rectangle(width=40, height=20)
created = Rectangle.create(30, 50)
actual_4 = {
"rect1_area": rect1.area(),
"rect1_wider_than_rect2": rect1.wider(rect2),
"rect2_wider_than_rect1": rect2.wider(rect1),
"created_debug": created.debug_compact(),
}
expected_4 = {
"rect1_area": 1500,
"rect1_wider_than_rect2": False,
"rect2_wider_than_rect1": True,
"created_debug": "Rectangle { width: 30, height: 50 }",
}
cases.append(dict(
name="struct_methods_and_associated_fn",
summary="Verify impl methods area(&self), wider(&self, &Rectangle), and Rectangle::create",
expected=expected_4,
actual=actual_4,
passed=actual_4 == expected_4,
))
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()
- 核对 ..base 移动非 Copy 字段 nation、Color/Point 下标访问与 UnitStruct 零大小、Rectangle {:?}/{:#?}、面积 1500、wider=false 及 Rectangle::create。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:bd14e6046384e46f35b56f7027226db969fa7a5d2f0a982f9fa1b5bb24ef6700
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:d0b82d3228fdc15878d588cb241972d8894762856b8c7e3ad9cf9cbe2ab73c55
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
结构体方法与关联函数的根本区别是什么?使用结构体更新语法 ..other 时,为什么有时原实例部分字段会失效?
展开参考解答
方法的首个参数是 self/&self/&mut self 并通过实例点号调用,关联函数不含 self 参数并通过 类型::函数 调用;..other 会将未显式覆盖的非 Copy 字段(如 String)的所有权移给新实例,从而使原实例这些字段不可再整体使用。