Modules, Visibility, and Crate Structure
local graph
Chapter 10 — Modules, Visibility, and Crate Structure
Section titled “Chapter 10 — Modules, Visibility, and Crate Structure”Ordo ab chao. (Order from chaos.)
As programs grow beyond a single file, organization becomes essential. Error types, traits, structs, and functions accumulate. Without structure, finding code becomes difficult, and understanding the relationships between components becomes impossible. Every language provides mechanisms for organizing code into units, controlling what is exposed to the outside world, and packaging code for distribution. Rust’s approach differs from the package and namespace systems familiar to object-oriented developers in ways that reflect the language’s emphasis on explicitness and compile-time verification.
Java organizes code into packages that mirror directory structures. C# uses namespaces that can span multiple files and assemblies. C++ has namespaces and header files with include guards. Rust uses modules, which can be defined inline or in separate files, with visibility rules that control access at a granular level. Crates serve as compilation units and distribution packages, roughly equivalent to Java’s JAR files or C#‘s assemblies.
Understanding Rust’s module system requires letting go of some assumptions. Modules are not namespaces in the C++ sense; they are hierarchical containers with enforced visibility boundaries. File structure relates to module structure, but the relationship is more flexible than Java’s package-per-directory approach. Visibility defaults to private, unlike Java’s package-private or C#‘s internal defaults.
These differences serve Rust’s goal of making APIs explicit and preventing accidental exposure of implementation details.
The module system
Modules group related definitions: structs, enums, traits, functions, constants, and other modules. A module creates a scope for names and a boundary for visibility. Items within a module can see each other freely, but items outside the module see only what the module explicitly exposes.
The mod keyword declares a module. The simplest form defines a module inline with its contents in curly braces:
mod authentication { pub struct User { username: String, password_hash: String, }
impl User { pub fn new(username: String, password: String) -> User { User { username, password_hash: hash_password(&password), } }
pub fn verify(&self, password: &str) -> bool { verify_hash(&self.password_hash, password) } }
fn hash_password(password: &str) -> String { // Implementation hidden from outside the module format!("hashed:{}", password) } fn verify_hash(hash: &str, password: &str) -> bool { hash == &format!("hashed:{}", password) }}The authentication module contains a User struct and associated functions. Outside this module, code can create users with authentication::User::new and verify passwords with the verify method. The hash_password and verify_hash functions are private to the module; external code cannot call them directly. The struct’s fields are also private; external code cannot access username or password_hash directly, only through the provided methods.
This encapsulation differs from object-oriented access modifiers in a subtle way. In Java or C#, private means private to the class. In Rust, private means private to the module. All code within the authentication module can access User’s fields directly, not just User’s own methods. Other structs or functions defined in the same module have the same access. The module, not the type, forms the privacy boundary.
Nested modules create hierarchies. A module can contain submodules, which can contain their own submodules:
mod services { pub mod authentication { pub struct Session { /* ... */ } }
pub mod authorization { pub struct Permission { /* ... */ } }
mod internal { // Private submodule, not visible outside services }}Code outside services accesses items through the full path:
services::authentication::Session. The internal submodule is
private to services; code outside services cannot even refer to it.
Visibility rules
Rust’s visibility system is more granular than most object-oriented languages. The pub keyword makes an item public, but “public” has nuances depending on context and modifiers.
An item without pub is private to its containing module. A struct defined without pub is invisible outside its module. A function without pub cannot be called from outside. Private is the default; visibility must be explicitly granted.
The pub keyword alone makes an item visible to any code that can see the containing module. If module A contains pub struct Foo, and module A is itself public, then Foo is visible wherever A is visible. If A is private to its parent module, Foo remains invisible outside that parent despite being declared pub.
The pub(crate) modifier restricts visibility to the current crate. An item marked pub(crate) is visible throughout the crate but invisible to code in other crates that depend on this one. This is useful for internal APIs that multiple modules need but external consumers should not access:
mod database { pub(crate) struct Connection { url: String, } pub(crate) fn connect(url: &str) -> Connection { Connection { url: url.to_string() } }}Other modules in the same crate can use Connection and connect, but a crate depending on this one cannot. The database internals remain implementation details.
The pub(super) modifier restricts visibility to the parent module. This is useful when a submodule needs to expose something to its parent but not to the wider crate:
mod services { mod helpers { pub(super) fn validate(input: &str) -> bool { // Only services module can call this !input.is_empty() } }
pub fn process(input: &str) -> Result<(), &'static str> { if helpers::validate(input) { Ok(()) } else { Err("Invalid input") } }}The helpers module exposes validate to the services module, but not beyond. Code outside services cannot call services::helpers::validate; it can only call services::process.
The pub(in path) modifier provides the most precise control, restricting visibility to a specific ancestor module:
mod app { mod services { mod internal { pub(in crate::app) fn utility() { // Visible anywhere in the app module } } }}This level of granularity is rarely needed, but it exists for complex module hierarchies where intermediate visibility levels are required.
The following diagram illustrates how visibility modifiers control access:
graph LR
EXT["external crate"]
subgraph CRATE["crate"]
OTHER["mod other"]
subgraph PARENT["mod parent"]
subgraph CHILD["mod child"]
F1["fn f1()"]
F2["pub fn f2()"]
F3["pub(crate) fn f3()"]
F4["pub(super) fn f4()"]
end
PC["parent code"]
end
end
F2 --> EXT
F2 --> OTHER
F2 --> PC
F3 --> OTHER
F3 --> PC
F4 --> PC
[!visual-conversion] Visibility modifiers control which code can access module items. Print diagram (PDF 272, printed p. 268) recreated in Mermaid; nesting (crate ⊃ mod parent ⊃ mod child) and every access arrow transcribed from an enlarged crop.
fn f1()has no outgoing arrow in print (private).
Struct field visibility
Struct fields have their own visibility, independent of the struct’s visibility. A struct can be public while its fields remain private:
pub struct Config { pub name: String, pub timeout: u64, secret_key: String, // Private field}External code can see Config exists and access its public fields, but cannot read or write secret_key. This pattern is common: expose the type for use in signatures while hiding implementation details.
When all fields are private, external code cannot construct the struct using literal syntax. The struct must provide a constructor function or implement Default:
impl Config { pub fn new(name: String, timeout: u64, secret_key: String) -> Self { Config { name, timeout, secret_key } }}This is not a limitation but a feature. The constructor can validate inputs, compute derived values, or enforce invariants. Forcing construction through a function rather than field-by-field initialization makes the type’s contract explicit.
Enum variants, by contrast, inherit their visibility from the enum itself. A pub enum has public variants; you cannot make some variants public and others private. This reflects enums’ role as discriminated unions: pattern matching on an enum requires knowing all variants, so hiding some would undermine the type’s usability.
Module organization in files
Section titled “Module organization in files”Inline module definitions work for small modules, but larger modules benefit from separate files. Rust provides two conventions for mapping modules to files.
The traditional convention places a module’s contents in a file named after the module. A mod authentication; declaration (note the semicolon instead of curly braces) tells the compiler to look for the module’s contents in a file named authentication.rs in the same directory, or in authentication/mod.rs for modules with submodules.
The modern convention (stabilized in Rust 2018) allows authentication.rs to exist alongside an authentication/ directory containing submodules. This avoids the proliferation of mod.rs files that made navigation confusing in earlier Rust.
Consider a project structure:
src/├── main.rs├── lib.rs├── config.rs├── database.rs├── services/│ ├── mod.rs # or services.rs in the parent│ ├── auth.rs│ └── storage.rsThe lib.rs declares the top-level modules:
pub mod config;pub mod database;pub mod services;The services/mod.rs (or services.rs) declares its submodules:
pub mod auth;pub mod storage;Each mod declaration tells the compiler to include that module’s contents from the corresponding file. The pub on each makes the modules visible to crate consumers.
Paths within the crate use crate:: as the root. A function in services/auth.rs can refer to the config module as crate::config. The super:: keyword refers to the parent module, useful for accessing sibling modules or parent-level items without spelling out the full path.
// In services/auth.rsuse crate::config::Config;use super::storage::Store; // Sibling module
pub fn authenticate(config: &Config, store: &Store) -> bool { // ...}The use statement brings items into scope, allowing shorter names. After use crate::config::Config, code can refer to Config without the full path. Multiple items from the same module can be imported with braces: use crate::config::{Config, Settings}. A glob import use crate::config::* brings everything public into scope, though this is discouraged for clarity.
Crates as deployment units
A crate is Rust’s unit of compilation and distribution. Every Rust project produces at least one crate. The distinction between library crates and binary crates matters for understanding how code is organized and shared.
A library crate produces code that other crates can depend on. It has a root at lib.rs and exposes a public API through its module structure. The crate’s public items become available to dependents under the crate’s name. If a crate named mylib exposes pub mod config with pub struct Settings, dependents access it as mylib::config::Settings.
A binary crate produces an executable. It has a root at main.rs (or files in src/bin/) containing a main function. Binary crates can depend on library crates, including a library crate in the same project, but cannot be depended upon by other crates.
A project can contain both. A common pattern is a library crate providing core functionality and a binary crate providing a command-line interface. The Cargo.toml manifests this structure:
[package]name = "myapp"version = "0.1.0"edition = "2021"
[lib]path = "src/lib.rs"
[[bin]]name = "myapp"path = "src/main.rs"The binary crate depends on the library crate implicitly. Code in main.rs can use myapp::whatever to access library items.
Multiple binary crates can exist in src/bin/, each becoming a separate executable. This is useful for projects with several related tools:
src/├── lib.rs├── main.rs└── bin/ ├── admin.rs └── worker.rsRunning cargo build produces executables for all binaries. Running cargo run —bin admin runs a specific one.
The prelude and re-exports
Rust’s standard library defines a prelude: a set of items automatically imported into every module. This includes fundamental types like Option, Result, Vec, and String, along with common traits like Clone, Copy, and Iterator. The prelude keeps code concise; without it, every file would begin with imports of basic types.
Crates can define their own preludes for common imports:
// In lib.rspub mod prelude { pub use crate::config::Config; pub use crate::error::Error; pub use crate::Result;}Users of the library can use mylib::prelude::* to get commonly needed items. This pattern appears in frameworks and libraries with many interdependent types.
Re-exports with pub use change where items appear in the public API. An item defined in crate::internal::details::Thing can be re-exported at crate::Thing:
// In lib.rsmod internal { pub mod details { pub struct Thing { /* ... */ } }}pub use internal::details::Thing;External code sees Thing at the crate root, unaware of the internal module structure. This decouples the public API from the implementation organization, allowing refactoring of internals without breaking dependent code.
Organizing larger projects
Small projects fit comfortably in a few files with a flat module structure. Larger projects benefit from deeper hierarchies and clearer separation between public API and implementation.
A layered approach groups modules by responsibility. A web service might have modules for HTTP handling, business logic, and data access, each with submodules for specific concerns:
src/├── lib.rs├── api/│ ├── mod.rs│ ├── routes.rs│ ├── middleware.rs│ └── handlers.rs├── domain/│ ├── mod.rs│ ├── models.rs│ └── services.rs├── storage/│ ├── mod.rs│ ├── postgres.rs│ └── redis.rsThe API layer depends on domain; domain depends on storage. Dependencies flow inward, with business logic isolated from HTTP concerns and database details.
The facade pattern applies naturally to module design. A module’s public API can be a curated subset of its contents, hiding implementation modules entirely:
mod routes;mod middleware;mod handlers;
pub use routes::configure;pub use handlers::AppState;
// src/api/handlers.rsuse super::middleware::authenticate;use crate::domain::services::UserService;
pub struct AppState { user_service: UserService,}
impl AppState { pub fn new(user_service: UserService) -> Self { AppState { user_service } }}
pub(super) fn handle_login(state: &AppState, credentials: Credentials) -> Response { // Uses authenticate from middleware // Uses user_service from domain Response::ok()}
// src/api/routes.rsuse super::handlers::{handle_login, AppState};
pub fn configure(app: &mut Router, state: AppState) { app.route("/login", post(|creds| handle_login(&state, creds)));}pub(super) fn authenticate(request: &Request) -> Result<User, AuthError> { // Only visible within api module todo!()}Code depending on the api module sees only configure and AppState, not the internal division into routes, middleware, and handlers. Changes to internal organization do not affect the public API.
Feature flags add another dimension to module organization. Cargo features enable conditional compilation, including or excluding modules based on build configuration:
[features]default = []postgres = ["sqlx/postgres"]redis = ["redis"]#[cfg(feature = "postgres")]pub mod postgres;
#[cfg(feature = "redis")]pub mod redis;Modules compile only when their features are enabled, reducing binary size and compile time for unused functionality. This is particularly valuable for libraries supporting multiple backends or optional capabilities.
Comparing with OOP approaches
Object-oriented languages typically tie visibility to class membership. Java’s private means private to the class; protected means accessible to subclasses; package-private (the default) means accessible within the package. C# follows a similar pattern with internal for assembly scope.
Rust’s module-based visibility has different tradeoffs. Multiple types in the same module share access to each other’s private members. This encourages grouping tightly coupled types together and separating loosely coupled ones. The lack of inheritance makes protected meaningless; there are no subclasses to protect.
The strictness of Rust’s defaults (private unless marked pub) catches accidental exposure that Java’s package-private default might miss. When everything requires explicit visibility declarations, API boundaries become intentional rather than accidental.
Re-exports allow decoupling of public API from implementation structure in ways that Java packages cannot achieve. Java’s package hierarchy is rigid: a class in com.example.internal is visible as such. Rust’s re-exports can present a flat API from a deep module tree, hiding implementation organization entirely.
Recap
Modules organize code into hierarchical scopes with enforced visibility boundaries. The mod keyword declares modules, either inline with curly braces or in separate files. Private is the default; visibility requires explicit pub declarations.
Visibility modifiers provide granular control. pub exposes items wherever the containing module is visible. pub(crate) limits visibility to the current crate. pub(super) limits visibility to the parent module. pub(in path) limits visibility to a specific ancestor.
Struct fields have independent visibility from the struct itself. Enum variants inherit the enum’s visibility. Private fields require constructor functions, enforcing type invariants at construction time.
Files map to modules through naming conventions. A mod foo; declaration looks for foo.rs or foo/mod.rs. The use keyword brings items into scope. pub use re-exports items, decoupling public API from internal organization.
Crates are compilation and distribution units. Library crates expose APIs for other crates; binary crates produce executables. A project can contain both, with the binary depending on the library. Preludes and re-exports shape how a crate presents itself to users.
The next chapter demystifies macros, Rust’s metaprogramming facility that enables code generation at compile time. Declarative macros and procedural macros extend the language in ways that reduce boilerplate and enable expressive APIs.