Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Modules and Crates: mod, pub Visibility, use Paths, and Workspaces

Modules decide privacy, crates decide compilation, workspaces decide sharing. The file layout, visibility levels and Cargo wiring that hold them together.

~4 min readRust
#Rust#Modules#Cargo
3D illustration of a Cargo workspace crate tree with module boundaries and public visibility gates

Quick Summary

A crate is the unit of compilation; a module is the unit of privacy. cargo new my-app creates a binary crate with one implicit root module (main.rs), cargo new my-lib --lib creates a library crate (lib.rs). Modules let you group items and control what is visible: everything is private to its parent module unless marked pub, and the tree of mod declarations defines the paths that use resolves against.

Visibility is not binary. pub(crate) exposes an item to the whole crate but not to dependents, pub(super) to the parent module, pub(in crate::api) to a specific ancestor. Library authors use these to keep a documented public surface while sharing helpers internally — this is the mechanism that makes "sealed" APIs possible.

A workspace is a set of crates sharing one Cargo.lock, one target/ directory, and one set of dependency versions. It is the standard layout once a project has more than one binary or a library plus a CLI, and it is what makes workspace.dependencies and unified feature resolution possible.

Basic Syntax & Signature

rust
// src/lib.rs — crate root of a library. pub mod api; // loads src/api.rs or src/api/mod.rs mod internal; // private: not reachable from other crates pub mod prelude; // a module that re-exports common items pub use api::Client; // re-export so callers write my_crate::Client pub const VERSION: &str = "0.1.0"; // src/api.rs use crate::internal::token::Token; // absolute path from the crate root use super::VERSION; // parent module (crate root here) use std::collections::HashMap; pub struct Client { tokens: HashMap<String, Token>, } impl Client { pub fn new() -> Self { Client { tokens: HashMap::new() } } pub(crate) fn insert_token(&mut self, key: &str, raw: &str) { self.tokens.insert(key.to_string(), Token::new(raw)); } pub fn token_len(&self, key: &str) -> Option<usize> { self.tokens.get(key).map(|t| t.expose_len()) } } // src/internal.rs pub(crate) mod token; // src/internal/token.rs pub(crate) struct Token(String); impl Token { pub(crate) fn new(raw: &str) -> Self { Token(raw.to_string()) } // Public within the crate is not enough for a `pub fn` return type // outside the module; expose only a length, not the secret. pub(crate) fn expose_len(&self) -> usize { self.0.len() } }

Paths follow three roots: crate:: (this crate's root), self:: (current module), super:: (parent, and super::super:: as far as needed). Since the 2018 edition, use paths must start with a crate name, crate, self, or super — the old use internal::token; form is gone, which is why 2015-edition snippets copied into modern code fail to resolve.

toml
# Workspace root Cargo.toml [workspace] members = ["crates/core", "crates/cli", "crates/server"] resolver = "2" [workspace.package] version = "0.3.0" edition = "2021" license = "MIT" [workspace.dependencies] serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
toml
# crates/core/Cargo.toml [package] name = "core-lib" version.workspace = true edition.workspace = true [dependencies] serde.workspace = true serde_json.workspace = true

cargo build -p core-lib, cargo test --workspace, and cargo run -p cli operate on the workspace from any member directory. Path dependencies between members are written core-lib = { path = "../core" }.

Key Comparison Table

VisibilityVisible fromTypical use
(none)Current module and its descendantsImplementation details
pub(self)Current module only (same as none)Explicit intent
pub(super)Parent module and its subtreeSibling helper modules
pub(crate)Entire crate, not dependentsInternal API shared across modules
pub(in crate::a::b)That ancestor's subtreeNarrow internal surfaces
pubEverywhere the crate is visibleDocumented public API
LayoutFile pathNote
mod foo; in lib.rssrc/foo.rsModern flat style
mod foo; in lib.rssrc/foo/mod.rsLegacy style; both work
mod bar; inside foo.rssrc/foo/bar.rsSubmodule of foo
mod bar; inside foo.rssrc/foo/bar/mod.rsSame, legacy
#[path = "other.rs"] mod bar;src/other.rsExplicit override
Crate unitRoot filemainPublishable
Binarysrc/main.rsRequiredYes, as a bin
Librarysrc/lib.rsNoneYes, as a lib
Integration testtests/*.rsNoneNo
Exampleexamples/*.rsRequiredNo
Benchmarkbenches/*.rsOptionalNo

Practical Edge Cases & Deep Dives

1. Re-exports keep the public path stable while files move

rust
// src/lib.rs mod client; mod config; pub mod prelude { pub use crate::client::Client; pub use crate::config::Config; } // Callers depend on `my_crate::prelude::Client`, not on `client::Client`, // so moving the file or renaming the module is not a breaking change.

This is the reason large crates like tokio and serde publish a small, deliberate public tree. Every pub path is API; every pub(crate) is free to change. A rule that works well: pub only what appears in documentation, pub(crate) for everything shared across modules.

2. The pub type in a private module error

rust
mod inner { pub struct Config { pub level: u8, } } // This is legal: the type is reachable through this re-export. pub use inner::Config; // Without the re-export, `pub fn make() -> inner::Config` compiles only if // `inner` is at least as visible as `make`; otherwise you get: // error[E0446]: private type `inner::Config` in public interface pub fn make() -> Config { Config { level: 1 } }

E0446 is the compiler enforcing "a public item cannot expose something less public than itself". The fix is either to widen the module (pub mod inner) or, better, to re-export the type at the level where it is intended to be used.

3. Sibling modules, super, and the privacy rule that surprises most

rust
mod a { pub fn helper() -> u8 { 1 } fn secret() -> u8 { 2 } pub mod nested { // Private items of the PARENT are visible to child modules. pub fn peek() -> u8 { super::secret() } } } mod b { pub fn call_a() -> u8 { // Sibling modules cannot see each other's private items, // but `a::helper` is pub, so this works. crate::a::helper() } // `crate::a::secret()` would fail: E0603, function is private. }

Privacy in Rust descends: a child module can see everything its ancestors have, and an ancestor can see a descendant's private items only from within the same module tree. This is why #[cfg(test)] mod tests placed inside a file can test private functions without any pub gymnastics.

4. use is not an import of the module graph — and the unused warning is real

rust
use std::collections::HashMap; // brings the name into scope // use std::collections::*; // glob: works, but hides what is used // Rename to avoid a collision: use std::fmt::Result as FmtResult; // A trait must be in scope for its methods to be callable: use std::io::Read; fn read_all(file: &mut std::fs::File) -> std::io::Result<Vec<u8>> { let mut buf = Vec::new(); file.read_to_end(&mut buf)?; // needs `use std::io::Read` Ok(buf) } fn map() -> HashMap<String, u8> { HashMap::new() } fn fmt_result() -> FmtResult { Ok(()) }

The unused_imports warning is worth obeying: a use of a trait that is never called usually means the code can be simplified, and a glob import hides exactly which items the module depends on. Prefer explicit imports, with pub use for re-exports.

5. A workspace with a shared library and two binaries

text
repo/ ├── Cargo.toml # [workspace] ├── Cargo.lock # one lock file for all members ├── crates/ │ ├── core/ (lib) │ ├── cli/ (bin: depends on core by path) │ └── server/(bin: depends on core by path)
toml
# crates/cli/Cargo.toml [package] name = "app-cli" version.workspace = true edition.workspace = true [dependencies] core-lib = { path = "../core" } tokio.workspace = true [[bin]] name = "app" path = "src/main.rs"
rust
// crates/cli/src/main.rs use core_lib::prelude::Client; // hyphen in package name -> underscore in code #[tokio::main] async fn main() -> anyhow::Result<()> { let client = Client::new(); println!("{}", client.token_len("missing").unwrap_or(0)); Ok(()) }

Two things to remember: a package named core-lib is imported as core_lib, and resolver = "2" in the workspace root is required for edition 2021 feature unification to behave per-target rather than globally. Without it, a dev-dependency's features can enable code in release builds.

6. Conditional compilation in the module tree

rust
#[cfg(target_os = "linux")] mod platform { pub fn open() -> &'static str { "epoll" } } #[cfg(not(target_os = "linux"))] mod platform { pub fn open() -> &'static str { "kqueue" } } #[cfg(test)] mod tests { #[test] fn platform_name_is_set() { assert!(!super::platform::open().is_empty()); } }

#[cfg(test)] on the module means it is not compiled into the library at all, only into the test harness. The same attribute is how #[cfg(feature = "serde")] gates optional integrations — and the reason a feature must be additive: enabling it in one dependency enables it for the whole build graph.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
E0432: unresolved importPath not rooted at crate/self/super/crate name, or module not declaredAdd mod foo; and use crate::foo::Bar
E0603: module is privatePath crosses a private moduleMake the module pub or re-export the item
E0446: private type in public interfacepub fn returns a type from a private moduleRe-export the type or widen the module
file not found for modulemod foo; declared but src/foo.rs missingCreate the file at the right depth (src/parent/foo.rs)
Two mod foo; declarationsDeclared in both lib.rs and main.rsDeclare once; share through the library crate
unused import warningTrait or item imported but unusedRemove it, or call the trait method
cannot find crate in a workspace memberMissing [dependencies] entryAdd path = "../other" dependency
Feature works in dev, missing in releaseresolver = "1" unificationSet resolver = "2" in the workspace root

One layout trap deserves a note: putting mod api; in main.rs of a binary means the module is compiled into the binary only, so tests/ cannot import it. Anything that needs testing belongs in lib.rs; the binary should be a thin main that calls the library.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.