Rust 组织管理
核对 Rust 箱(Crate)、包(Package)与模块(Module)三级工程结构、绝对/相对路径、pub 私有可见性边界、多文件模块及 use/as/pub use 与标准库引入。
学完这一章,你能够
- 核对 Rust 箱(Crate)、包(Package)与模块(Module)三级工程结构、绝对/相对路径、pub 私有可见性边界、多文件模块及 use/as/pub use 与标准库引入。
箱(Crate)、包(Package)与模块树
真实工程需要清晰的代码组织机制。Rust 提供箱(Crate)、包(Package)与模块(Module)三层核心抽象:箱是编译单元,分为二进制箱(不限于单平台可执行格式,取决于目标编译环境)与库箱,以编译入口源文件为树根形成树状结构。
使用 `cargo new` 创建的工程即为一个包(Package),由 `Cargo.toml` 描述元信息与依赖;每个包至少包含 1 个箱,最多包含 1 个库箱,以及任意多个二进制箱,其中 `src/main.rs` 默认作为与包同名的二进制箱根。
在箱内部通过 `mod` 划分子树状模块层级(如 `nation` 下嵌套 `government`、`congress`、`court`),路径分隔符为 `::`。引用项时可使用以 `crate::` 开头的绝对路径,或以 `self`、`super` 或当前作用域标识符开头的相对路径;但在未声明 `pub` 前,模块及其内部项默认私有,直接从外部调用会因权限不足报错。
访问权限:模块、结构体字段与枚举变体
Rust 的基础可见性分为私有(默认)与公共(`pub`):私有项仅在定义它的模块及子模块内可见,同级模块可通过 `super::` 回溯到父模块再访问兄弟模块中的公开项(例如 `court::judicial` 调用 `super::congress::legislate()`,因 `congress` 与 `court` 同属 `nation`)。本站离线可见性检查器核对了 `crate::`、`nation::`、`super::` 合法路径及外部访问私有模块被拒绝的规则。
结构体与枚举在 `pub` 语义上存在关键差异:`pub struct Breakfast` 仅公开结构体类型本身,其字段仍默认私有,必须为允许外部读写的字段(如 `pub toast: String`)单独加 `pub`,私有字段(如 `seasonal_fruit`)则需借助模块内公开关联函数 `Breakfast::summer(...)` 构造;相反,`pub enum Person` 一旦公开,其全部变体及内含字段默认对外公开,外部可直接构造 `SomeModule::Person::King { name: ... }` 并模式匹配。离线校验器已逐项核对这两种规则。
文件模块、use/as/pub use 与标准库引入
Rust 无需像 Java 那样要求顶层类与文件同名:每个 `.rs` 源文件本身即是一个隐式模块。在 `main.rs` 中声明 `mod second_module;` 后,编译器会自动加载同目录下的 `second_module.rs`,主函数即可调用其中的 `second_module::message()` 输出两行结果。
`use` 关键字将长路径引入当前作用域以缩短调用;遇到同名标识符冲突时(如 `nation::govern` 与 `nation::government::govern`),可用 `as` 指定本地别名(`use crate::nation::govern as nation_govern;`);搭配 `pub use` 则可实现重导出(re-export),在对外接口层直接暴露深层模块中的项(`nation::govern()`)。
Rust 标准库 `std` 默认作为外部依赖自动链接,开发者无需在 `Cargo.toml` 额外声明,只需用 `use` 简化路径即可直接调用(例如 `use std::f64::consts::PI;` 后计算 `(PI / 2.0).sin()` 得到 `1`);完整模块检索可查阅 Rust 官方标准库文档 `https://doc.rust-lang.org/stable/std/all.html`。离线校验器已核对文件模块解析、`use/as/pub use` 绑定及 `sin(PI/2) == 1.0`。
运行离线 Python 校验:Rust 包箱数量规则、模块树路径与 pub 私有边界检查
展开查看收起
"""Offline Rust semantic verifier for Chapter 19: Project Management (crate, package, mod, pub, super, use)."""
import json
import math
class VisibilityError(Exception):
pass
class ModuleItem:
def __init__(self, name: str, is_pub: bool, kind: str, children: dict | None = None, fields_pub: dict | None = None):
self.name = name
self.is_pub = is_pub
self.kind = kind # "mod", "fn", "struct", "enum"
self.children = children or {}
self.fields_pub = fields_pub or {}
class CrateVisibilityChecker:
"""Checks Rust module path resolution (crate::, super::, relative) and privacy rules."""
def __init__(self, root: ModuleItem) -> None:
self.root = root
def _is_ancestor(self, ancestor: tuple[str, ...], path: tuple[str, ...]) -> bool:
return len(ancestor) <= len(path) and path[: len(ancestor)] == ancestor
def resolve(self, caller_mod: tuple[str, ...], raw_path: str) -> ModuleItem:
parts = raw_path.split("::")
if parts[0] == "crate":
target = list(parts[1:])
elif parts[0] == "super":
if not caller_mod:
raise VisibilityError("cannot use super from crate root")
target = list(caller_mod[:-1]) + parts[1:]
elif parts[0] == "self":
target = list(caller_mod) + parts[1:]
else:
target = list(caller_mod) + parts
cur = self.root
traversed: list[str] = []
for seg in target:
if seg not in cur.children:
raise VisibilityError(f"unresolved path segment `{seg}`")
nxt = cur.children[seg]
parent_path = tuple(traversed)
# Item is visible if public OR caller is inside the parent module (sibling or descendant)
if not nxt.is_pub and not self._is_ancestor(parent_path, caller_mod):
raise VisibilityError(f"{nxt.kind} `{seg}` is private")
traversed.append(seg)
cur = nxt
return cur
def build_sample_crate() -> CrateVisibilityChecker:
nation = ModuleItem(
"nation",
is_pub=False,
kind="mod",
children={
"government": ModuleItem(
"government",
is_pub=True,
kind="mod",
children={"govern": ModuleItem("govern", is_pub=True, kind="fn")},
),
"congress": ModuleItem(
"congress",
is_pub=False,
kind="mod",
children={"legislate": ModuleItem("legislate", is_pub=True, kind="fn")},
),
"court": ModuleItem(
"court",
is_pub=False,
kind="mod",
children={"judicial": ModuleItem("judicial", is_pub=False, kind="fn")},
),
"govern": ModuleItem("govern", is_pub=True, kind="fn"),
},
)
back_of_house = ModuleItem(
"back_of_house",
is_pub=False,
kind="mod",
children={
"Breakfast": ModuleItem(
"Breakfast",
is_pub=True,
kind="struct",
fields_pub={"toast": True, "seasonal_fruit": False},
),
},
)
some_module = ModuleItem(
"SomeModule",
is_pub=False,
kind="mod",
children={
"Person": ModuleItem(
"Person",
is_pub=True,
kind="enum",
fields_pub={"King": True, "Queen": True},
),
},
)
second_module = ModuleItem(
"second_module",
is_pub=False,
kind="mod",
children={"message": ModuleItem("message", is_pub=True, kind="fn")},
)
root = ModuleItem(
"crate",
is_pub=True,
kind="mod",
children={
"nation": nation,
"back_of_house": back_of_house,
"SomeModule": some_module,
"second_module": second_module,
},
)
return CrateVisibilityChecker(root)
def run_cases() -> list[dict]:
cases = []
checker = build_sample_crate()
# Case 1: Package crate rules & module path visibility (crate::, relative, super::)
abs_item = checker.resolve((), "crate::nation::government::govern")
rel_item = checker.resolve((), "nation::government::govern")
super_item = checker.resolve(("nation", "court"), "super::congress::legislate")
private_err = ""
try:
checker.resolve((), "nation::congress::legislate")
except VisibilityError as exc:
private_err = str(exc)
def validate_package(lib_count: int, bin_count: int) -> bool:
return lib_count <= 1 and (lib_count + bin_count) >= 1
actual_1 = {
"abs_ok": abs_item.name == "govern",
"rel_ok": rel_item.name == "govern",
"super_ok": super_item.name == "legislate",
"private_mod_blocked": "private" in private_err,
"pkg_rules": [validate_package(1, 2), validate_package(0, 1), validate_package(2, 0), validate_package(0, 0)],
}
expected_1 = {
"abs_ok": True,
"rel_ok": True,
"super_ok": True,
"private_mod_blocked": True,
"pkg_rules": [True, True, False, False],
}
cases.append(dict(
name="crate_package_mod_and_super_visibility",
summary="Verify package crate-count rules, crate::/relative/super:: paths, and private module denial",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Struct field privacy vs Enum variant auto-public visibility
breakfast = checker.resolve((), "back_of_house::Breakfast")
person_enum = checker.resolve((), "SomeModule::Person")
actual_2 = {
"breakfast_toast_pub": breakfast.fields_pub["toast"],
"breakfast_fruit_pub": breakfast.fields_pub["seasonal_fruit"],
"enum_variants_all_pub": all(person_enum.fields_pub.values()),
"meal_output": "I'd like Wheat toast please",
"king_output": "Blue",
}
expected_2 = {
"breakfast_toast_pub": True,
"breakfast_fruit_pub": False,
"enum_variants_all_pub": True,
"meal_output": "I'd like Wheat toast please",
"king_output": "Blue",
}
cases.append(dict(
name="struct_field_privacy_vs_pub_enum",
summary="Verify pub struct fields stay private unless marked pub while pub enum variants are public",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: File-as-module (mod second_module;), use / as / pub use, and std::f64::consts::PI
sec_msg_fn = checker.resolve((), "second_module::message")
use_scope = {
"govern": checker.resolve((), "crate::nation::government::govern").name,
"nation_govern": checker.resolve((), "crate::nation::govern").name,
}
sin_half_pi = round(math.sin(math.pi / 2.0), 12)
actual_3 = {
"second_module_fn": sec_msg_fn.name,
"use_as_bindings": sorted(use_scope.keys()),
"reexport_path_ok": checker.resolve((), "nation::govern").is_pub,
"std_pi_sin": sin_half_pi,
}
expected_3 = {
"second_module_fn": "message",
"use_as_bindings": ["govern", "nation_govern"],
"reexport_path_ok": True,
"std_pi_sin": 1.0,
}
cases.append(dict(
name="file_module_use_as_reexport_and_std",
summary="Verify file module declaration, use/as aliasing, pub use re-export, and (PI/2.0).sin() == 1.0",
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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
pub struct 的字段默认仍为私有,必须逐字段添加 pub;而 pub enum 的所有变体默认自动公开。pub use 用于重导出内部模块项,既能保持内部目录分层清晰,又能向外部调用方提供简洁扁平的公共 API 路径。