"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/rust-struct-lab/explore-struct.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-struct.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1220.zip