Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Crates and Modules
crate 与模块

What you’ll learn: How Rust code organization maps to Java packages, modules, and artifacts.
本章将学习: Rust 的代码组织方式,如何对应 Java 的 package、module 和构建产物。

Difficulty: 🟢 Beginner
难度: 🟢 初级

Rust organizes code around crates and modules rather than packages and classpaths.
Rust 围绕 crate 和模块组织代码,而不是围绕 package 和 classpath。

Mental Mapping
心智映射

Java idea
Java 概念
Rust idea
Rust 概念
artifact or module
产物或模块
crate
packagemodule tree
模块树
package-private or public API
包级或公开 API
module privacy plus pub
模块私有性加 pub

Basic Layout
基本结构

src/
├── main.rs
├── lib.rs
├── api.rs
└── model/
    └── user.rs

Visibility
可见性

  • items are private by default
    默认私有。
  • pub exposes an item more broadly
    pub 让条目向更外层暴露。
  • pub(crate) exposes within the current crate
    pub(crate) 只在当前 crate 内可见。

This default privacy is stricter than typical Java codebases and often leads to cleaner boundaries.
这种默认私有性通常比常见 Java 代码库更严格,但也经常能逼出更干净的边界。

Guidance
建议

  • keep module trees shallow at first
    前期模块树不要搞太深。
  • design crate boundaries around ownership of concepts, not around arbitrary layering
    crate 边界围绕概念归属来设计,不要只按机械分层切。
  • expose a small public API and keep the rest internal
    公开 API 尽量小,其余内容尽量内部化。

Crates and modules are simpler than many Java build layouts, but they reward deliberate boundary design.
crate 与模块比很多 Java 构建布局都简单,但它很奖励那种边界清楚的设计方式。