Rust 面向对象
核对 Rust 如何以模块与 pub 可见性实现封装、以结构体/枚举加 impl 组织数据与方法、以特性(Trait)与特征对象实现多态以及以组合替代传统类继承。
学完这一章,你能够
- 核对 Rust 如何以模块与 pub 可见性实现封装、以结构体/枚举加 impl 组织数据与方法、以特性(Trait)与特征对象实现多态以及以组合替代传统类继承。
封装:模块边界与结构体/枚举抽象
面向对象编程的核心诉求通常包含数据封装、行为抽象与多态。Rust 并非传统意义上的基于类的面向对象语言,但通过模块系统、结构体/枚举与特性(Trait)同样能完整落地这些工程范式。在最外层,每个 `.rs` 文件都是一个模块,配合 `pub` 可精确控制哪些类型与方法对外可见;在类型层,用 `pub struct` 或 `pub enum` 封装状态数据,并在 `impl` 块内为其绑定操作方法(需注意:在标准 Rust 语法中 `impl` 关键字前不能加 `pub`,可见性修饰符 `pub` 应分别标注在各个对外方法或关联函数前)。
以 `second.rs` 中的 `pub struct ClassName { field: i32 }` 为例:私有字段 `field` 对外部模块不可直接读写,只能经公开关联函数 `ClassName::new(1024)` 构造,再调用公开方法 `public_method(&self)`(内部再调用私有辅助方法 `private_method(&self)`),依次输出 `from public method` 与 `from private method`。本站离线校验器已核对外部读取私有字段被拒及公开方法链式调用私有方法的输出。
多态与组合:以 Trait 和结构体组合替代传统继承
Rust 有意不提供类似 Java `extends` 的单继承或字段继承语法糖,而是将“接口多态”与“代码复用”拆分为两种更清晰的机制:需要处理多种异构类型时,通过定义 `trait` 配合泛型边界(静态派发)或特征对象 `Vec<Box<dyn Trait>>`(动态派发)实现多态;需要复用另一类型的数据字段与行为时,推荐在“子”结构体中以组合方式持有一个“父”结构体字段并委托方法调用。离线校验器已同时验证 `Box<dyn Drawable>` 异构动态派发(`Button` 与 `SelectBox`)以及结构体组合委托模式。
运行离线 Python 校验:Rust 模块封装、Trait Object 动态派发与结构体组合
"""Offline Rust semantic verifier for Chapter 25: Object-Oriented Patterns (encapsulation, trait-object dyn dispatch, composition)."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
import json
class AccessDeniedError(Exception):
pass
class ClassName:
"""Models second.rs::ClassName with private field + private_method encapsulated behind pub API."""
def __init__(self, value: int) -> None:
self._field = value # private to module `second`
@classmethod
def new(cls, value: int) -> "ClassName":
return cls(value)
def public_method(self) -> list[str]:
log = ["from public method"]
log.append(self._private_method())
return log
def _private_method(self) -> str:
return "from private method"
def external_get_field(self, same_module: bool) -> int:
if not same_module:
raise AccessDeniedError("field `field` of struct `ClassName` is private")
return self._field
class Drawable(ABC):
"""Models a Rust object-safe trait used via Box<dyn Drawable>."""
@abstractmethod
def draw(self) -> str: ...
@dataclass
class Button(Drawable):
width: int
height: int
label: str
def draw(self) -> str:
return f"Button({self.width}x{self.height}, {self.label})"
@dataclass
class SelectBox(Drawable):
options: list[str]
def draw(self) -> str:
return f"SelectBox({','.join(self.options)})"
@dataclass
class BaseWidget:
id: str
def tag(self) -> str:
return f"widget:{self.id}"
@dataclass
class ComposedPanel:
"""Models Rust composition (has-a) in place of classical class field inheritance."""
base: BaseWidget
title: str
def render_header(self) -> str:
return f"{self.base.tag()}|{self.title}"
def run_cases() -> list[dict]:
cases = []
# Case 1: Module + struct encapsulation (pub new/public_method calling private_method)
obj = ClassName.new(1024)
output_lines = obj.public_method()
external_blocked = False
try:
obj.external_get_field(same_module=False)
except AccessDeniedError:
external_blocked = True
actual_1 = {
"public_call_output": output_lines,
"external_private_field_blocked": external_blocked,
"internal_field_value": obj.external_get_field(same_module=True),
}
expected_1 = {
"public_call_output": ["from public method", "from private method"],
"external_private_field_blocked": True,
"internal_field_value": 1024,
}
cases.append(dict(
name="module_struct_encapsulation",
summary="Verify pub constructor/method invokes private_method while external module cannot access private field",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Polymorphism via heterogeneous Vec<Box<dyn Drawable>> trait objects
screen_components: list[Drawable] = [
Button(width=80, height=30, label="OK"),
SelectBox(options=["Rust", "Cargo"]),
]
rendered = [comp.draw() for comp in screen_components]
actual_2 = {
"component_count": len(rendered),
"dyn_dispatch_output": rendered,
}
expected_2 = {
"component_count": 2,
"dyn_dispatch_output": ["Button(80x30, OK)", "SelectBox(Rust,Cargo)"],
}
cases.append(dict(
name="trait_object_dynamic_dispatch",
summary="Verify heterogeneous Vec<Box<dyn Drawable>> dynamic dispatch across Button and SelectBox",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Composition over classical inheritance
panel = ComposedPanel(base=BaseWidget("nav-1"), title="Settings")
actual_3 = {
"composed_header": panel.render_header(),
"delegated_base_tag": panel.base.tag(),
}
expected_3 = {
"composed_header": "widget:nav-1|Settings",
"delegated_base_tag": "widget:nav-1",
}
cases.append(dict(
name="composition_over_inheritance",
summary="Verify Rust embeds parent struct as field to reuse state/behavior without class inheritance",
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()
- 核对 ClassName 外部私有字段拦截与双行输出、异构 Button/SelectBox 动态派发以及 ComposedPanel 组合委托。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:d6e41caabd2a326b9c0e5680029e45d24a7460002f6df70befab0ef22341d5eb
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:905a2500272adaf01dc29aaaf476e04a751af1b162b67490fe8710b0bc83be7b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 Rust 中不能写 pub impl ClassName,而应将 pub 写在具体方法上?当需要把多种不同类型放进同一个 Vec 统一调用 draw() 时应使用什么机制?
展开参考解答
Rust 语法规定固有 impl 块本身没有独立可见性修饰,必须按方法粒度使用 pub fn 决定哪些行为对外暴露;要在同一 Vec 中容纳多种异构类型并统一多态调用,应使用 trait object(例如 Vec<Box<dyn Drawable>>)。