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.

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
// 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.
# 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"] }# crates/core/Cargo.toml
[package]
name = "core-lib"
version.workspace = true
edition.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = truecargo 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
| Visibility | Visible from | Typical use |
|---|---|---|
| (none) | Current module and its descendants | Implementation details |
pub(self) | Current module only (same as none) | Explicit intent |
pub(super) | Parent module and its subtree | Sibling helper modules |
pub(crate) | Entire crate, not dependents | Internal API shared across modules |
pub(in crate::a::b) | That ancestor's subtree | Narrow internal surfaces |
pub | Everywhere the crate is visible | Documented public API |
| Layout | File path | Note |
|---|---|---|
mod foo; in lib.rs | src/foo.rs | Modern flat style |
mod foo; in lib.rs | src/foo/mod.rs | Legacy style; both work |
mod bar; inside foo.rs | src/foo/bar.rs | Submodule of foo |
mod bar; inside foo.rs | src/foo/bar/mod.rs | Same, legacy |
#[path = "other.rs"] mod bar; | src/other.rs | Explicit override |
| Crate unit | Root file | main | Publishable |
|---|---|---|---|
| Binary | src/main.rs | Required | Yes, as a bin |
| Library | src/lib.rs | None | Yes, as a lib |
| Integration test | tests/*.rs | None | No |
| Example | examples/*.rs | Required | No |
| Benchmark | benches/*.rs | Optional | No |
Practical Edge Cases & Deep Dives
1. Re-exports keep the public path stable while files move
// 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
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
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
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
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)# 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"// 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
#[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 / symptom | Cause | Fix |
|---|---|---|
E0432: unresolved import | Path not rooted at crate/self/super/crate name, or module not declared | Add mod foo; and use crate::foo::Bar |
E0603: module is private | Path crosses a private module | Make the module pub or re-export the item |
E0446: private type in public interface | pub fn returns a type from a private module | Re-export the type or widen the module |
file not found for module | mod foo; declared but src/foo.rs missing | Create the file at the right depth (src/parent/foo.rs) |
Two mod foo; declarations | Declared in both lib.rs and main.rs | Declare once; share through the library crate |
unused import warning | Trait or item imported but unused | Remove it, or call the trait method |
cannot find crate in a workspace member | Missing [dependencies] entry | Add path = "../other" dependency |
| Feature works in dev, missing in release | resolver = "1" unification | Set 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 toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.