Skip to content
RustLearn

Module 10 — Modules, Crates & Project Layout

Goal

Organize a real project: the module tree, visibility, paths, workspaces, dependencies, and publishing a crate to crates.io.

Start here — what this module is really about

Everything so far fitted in one file. Real programs do not, and this module is how Rust organises them. There are three words to get straight, and they nest:

  • A crate is the unit the compiler builds: one library, or one executable. Your project is a crate; every dependency you add is a crate.
  • A module is a namespace inside a crate — a way to group related code and control what the rest of the world can see. Modules can contain modules.
  • A package is what Cargo manages: a Cargo.toml plus one or more crates.

The rule that makes it all work is privacy: in Rust, everything is private by default. A function, struct, field or module is visible only inside the module that declares it, unless you write pub. That is stricter than most languages, and it is the useful direction to be strict in — you decide deliberately what your code promises to the outside world, and everything else stays yours to change.

The second half of the module is about the outside world in the other direction: adding dependencies from crates.io, laying out a project that has grown past one file, and writing documentation that the compiler tests for you.

A word of reassurance: the module system is the part of Rust people find fiddly rather than hard. The error messages are clear, the rules are mechanical, and once a project is laid out you rarely think about it again.

The one sentence to remember: a crate is what gets compiled, modules are namespaces inside it, and nothing is public unless you say pub.

Learning objectives

  • Explain packages, crates, modules, and paths
  • Control visibility with pub, pub(crate), and privacy defaults
  • Split code across files and directories correctly
  • Use use, as, pub use (re-export), and nested imports
  • Structure a real project with a library + binary
  • Manage dependencies, features, and workspaces

10.1 The vocabulary

TermMeaning
PackageOne Cargo.toml. Can contain many crates.
CrateA compilation unit. Either a binary (has main) or a library.
Crate rootsrc/main.rs (binary) or src/lib.rs (library).
ModuleA namespace inside a crate, declared with mod.
PathHow you name an item: crate::garden::vegetables::Asparagus.

Default package layout Cargo understands with no configuration:

my_package/
├── Cargo.toml
└── src/
    ├── lib.rs            # library crate  -> `my_package`
    ├── main.rs           # binary crate   -> `my_package`
    └── bin/
        ├── tool_a.rs     # extra binary   -> `tool_a`
        └── tool_b.rs     # extra binary   -> `tool_b`
tests/                    # integration tests, one crate per file
benches/                  # benchmarks
examples/                 # example programs, run with `cargo run --example foo`

Analogy — building, floors, rooms

A crate is the building — the unit that gets built, shipped and addressed. Modules are the floors and rooms inside it, and pub is which doors are unlocked to visitors. A workspace is the campus: several buildings sharing one car park and one set of ground rules.

10.2 Declaring modules

Inline:

rust
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
        fn seat_at_table() {}           // private
    }

    mod serving {
        fn take_order() {}
    }
}

pub fn eat_at_restaurant() {
    crate::front_of_house::hosting::add_to_waitlist();   // absolute path
    front_of_house::hosting::add_to_waitlist();          // relative path
}

Privacy rules

  • Everything is private by default, including modules, functions, structs, fields, and enum variants... with one exception: enum variants are public if the enum is.
  • A child module can see everything in its ancestors. A parent cannot see into a child's private items.
  • pub makes an item visible to the parent module; you must mark every level of the path.
rust
pub struct Breakfast {
    pub toast: String,        // public field
    seasonal_fruit: String,   // private field — outsiders can't set or read it
}

impl Breakfast {
    pub fn summer(toast: &str) -> Breakfast {   // so you need a constructor
        Breakfast { toast: toast.to_string(), seasonal_fruit: String::from("peaches") }
    }
}

pub enum Appetizer { Soup, Salad }   // both variants are public automatically

Visibility modifiers:

rust
pub                // visible everywhere the module is
pub(crate)         // visible anywhere in this crate — the workhorse
pub(super)         // visible to the parent module
pub(in crate::a)   // visible in a specific module subtree
                   // (no modifier) private to this module and its descendants

super:: navigates upward, like .. in a filesystem:

rust
fn deliver_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::deliver_order();
    }
    fn cook_order() {}
}

10.3 Splitting into files

mod foo; (with a semicolon, no body) tells the compiler to load the module from a file.

Modern style (Rust 2018+):

src/
├── lib.rs
├── front_of_house.rs           # module `front_of_house`
└── front_of_house/
    ├── hosting.rs              # module `front_of_house::hosting`
    └── serving.rs
rust
// src/lib.rs
mod front_of_house;
pub use crate::front_of_house::hosting;

// src/front_of_house.rs
pub mod hosting;
pub mod serving;

// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}

Older style used front_of_house/mod.rs instead of front_of_house.rs. Both work; the newer one is preferred because you don't end up with fifteen tabs called mod.rs.

Gotcha

Files are not automatically modules. If you create src/utils.rs and never write mod utils;, the file is simply not compiled. This surprises everyone once.


One idea, three files — how the pieces connect

The thing that confuses people is that mod does two different-looking jobs. Here is a small crate:

text
src/
├── main.rs
├── config.rs
└── network/
    ├── mod.rs        (or network.rs beside the folder, in modern style)
    └── client.rs
rust
// main.rs
mod config;            // "there is a module called config — load it from config.rs"
mod network;           // "...and one called network — load network/mod.rs"

use config::Settings;  // bring a name into scope so I can write `Settings`

fn main() {
    let s = Settings::load();
    network::client::connect(&s);
}

The two keywords are doing different things, and mixing them up is the classic beginner error:

  • mod name; declares a module and tells the compiler to go find its file. You write it once, in the parent.
  • use path::to::Thing; does not load anything — it is a shortcut so you can write Thing instead of the full path. You can write as many as you like, anywhere.

So: mod builds the tree; use gives you shorter names within it. If the compiler says "file not found for module", you wrote mod and there is no matching file. If it says "unresolved import", the module exists but the path or the pub is wrong.

10.4 use and re-exports

rust
use std::collections::HashMap;              // bring a type into scope
use std::io::Result as IoResult;            // rename to avoid collisions
use std::collections::{HashMap, HashSet};   // nested
use std::io::{self, Write};                 // io AND io::Write
use std::collections::*;                    // glob — avoid except in tests/preludes

Idiomatic depth: bring functions' parent module into scope, but bring types in directly:

rust
use std::collections::HashMap;
let mut m = HashMap::new();          // ✅ types: import the type

use std::io;
io::stdin();                         // ✅ functions: keep the module prefix so the
                                     //    call site says where it came from

Re-exporting with pub use

rust
// src/lib.rs
mod front_of_house;
pub use crate::front_of_house::hosting;    // external users can now write
                                           // my_crate::hosting::add_to_waitlist()

pub use decouples your internal file structure from your public API. Organize internals however you like, then present a flat, friendly surface:

rust
// src/lib.rs
mod error;
mod client;
mod config;

pub use error::{Error, Result};
pub use client::Client;
pub use config::{Config, ConfigBuilder};

This is what nearly every good crate does. Look at how serde or reqwest exposes a handful of names from a large internal tree.


pub use — designing the front door

Inside a crate, a natural layout often buries useful things:

rust
// src/lib.rs
mod parser;
mod tokens;
mod errors;

A user then has to write mycrate::parser::ast::Node, which exposes your internal structure — and locks you into it, because moving Node later breaks their code.

The fix is a re-export:

rust
// src/lib.rs
mod parser;
mod tokens;
mod errors;

pub use parser::ast::Node;      // now available as mycrate::Node
pub use errors::ParseError;

Two things happen at once. Your users get a short, stable path (mycrate::Node). And you keep the freedom to reorganise parser internally, because their code never named your internals — only the front door you published.

This is why well-designed crates have a flat, obvious top level regardless of how they are structured inside, and it is worth doing in your own projects the moment they grow past a couple of files.

Analogy — the sign in the lobby

use is not moving a room closer; it is pinning a shortcut in the lobby so you can stop reciting the full address every time. A re-export (pub use) goes further — it is the building's directory deliberately advertising a room on the third floor as if it were on the ground floor, so visitors never learn your internal floor plan and you stay free to rearrange it.

10.5 A realistic project layout

myapp/
├── Cargo.toml
├── src/
│   ├── main.rs              # thin: arg parsing + calls into the library
│   ├── lib.rs               # the real API
│   ├── config.rs
│   ├── error.rs
│   └── engine/
│       ├── mod.rs           # or engine.rs alongside engine/
│       ├── parser.rs
│       └── executor.rs
├── tests/
│   └── integration.rs       # sees only the PUBLIC API of the library
└── examples/
    └── basic.rs
rust
// src/lib.rs
pub mod config;
pub mod error;
mod engine;

pub use engine::run;
pub use error::{Error, Result};

// src/main.rs
use myapp::{run, Result};

fn main() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    run(&args)
}

Why split lib + bin? Integration tests, benchmarks, examples, and other crates can only use a library. Keeping main.rs to a dozen lines makes everything else testable.

10.6 Dependencies

toml
[package]
name = "myapp"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
rand = "0.8"
local_crate = { path = "../local_crate" }
some_git_dep = { git = "https://github.com/user/repo", tag = "v1.2" }

[dev-dependencies]           # only for tests, benches, examples
criterion = "0.5"

[features]
default = ["json"]
json = ["dep:serde_json"]

Version requirements are caret by default: "1.2.3" means >=1.2.3, <2.0.0. cargo update moves within that range; Cargo.lock pins exact versions.

Feature flags in your own crate

rust
#[cfg(feature = "json")]
pub mod json_support {
    pub fn to_json() {}
}

Users opt in with cargo add myapp --features json or myapp = { version = "1", features = ["json"] }.

Workspaces — multiple crates, one build

toml
# Cargo.toml at the repo root
[workspace]
members = ["core", "cli", "web"]
resolver = "2"

[workspace.dependencies]
serde = "1.0"
toml
# core/Cargo.toml
[dependencies]
serde = { workspace = true }

All members share one target/ directory and one Cargo.lock. cargo test at the root runs everything. This is how nearly all large Rust projects are organized.

10.7 Documentation

rust
//! # My Crate
//!
//! Inner doc comment — documents the *containing* item (put at the top of lib.rs).

/// Adds two numbers.
///
/// # Examples
///
/// ```
/// let sum = my_crate::add(2, 3);
/// assert_eq!(sum, 5);
/// ```
///
/// # Panics
/// Panics if the result overflows.
pub fn add(a: i32, b: i32) -> i32 { a + b }

cargo doc --open builds HTML. Code in ``` blocks is compiled and run by cargo test — your documentation cannot rot silently. That's covered fully in module 16.


Documentation that cannot go stale

Rust's documentation comments are worth adopting immediately, because of one property no other mainstream language has by default:

rust
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = mycrate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
  • /// documents the item that follows; //! documents the enclosing module or crate.
  • cargo doc --open renders it as a browsable site, same style as the standard library docs.
  • cargo test runs the code in those examples. If you change the signature and forget the doc, the build fails.

That last point is the whole argument. A README example is a promise nobody verified; a doc example is a test. Writing the example first, before the implementation, is also the fastest way to notice that an API is unpleasant to use — you feel it while typing the call.

Analogy — documentation that is checked at the door

Comments are notes pinned to a wall: nobody notices when they go stale. Rust's doc examples are run as tests on every build, so a lie in the documentation fails the build like any other broken code. Documentation you cannot forget to update is a different category of thing from documentation you promise to update.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
crateThe unit of compilation: one library or one executable.
binary crateA crate with main.rs that produces an executable.
library crateA crate with lib.rs that others depend on.
packageWhat Cargo.toml describes — one or more crates.
module (mod)A namespace inside a crate, controlling visibility.
pubMakes an item visible outside its module.
pathHow you name an item: std::collections::HashMap.
useBrings a path into scope so you can use a short name.
re-export (pub use)Publishing an internal item at a friendlier public path.
crate:: / super:: / self::Path roots: crate root, parent module, current module.
workspaceSeveral packages built together, sharing one lockfile and output directory.
crates.ioThe public registry Cargo downloads dependencies from.
semantic versioningThe major.minor.patch rule Cargo uses to decide compatible updates.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0583]: file not found for moduleYou wrote mod name; but there is no name.rs or name/mod.rs.Create the file, or fix the name. Files must match the module name exactly.
error[E0433]: failed to resolve: use of undeclared crate or moduleThe path root is wrong.Start from crate:: for an absolute path, or super:: to go up one level.
error[E0603]: ... is privateThe item exists but was never made public.Add pub — and remember every module along the path must be pub too.
error[E0432]: unresolved importThe use path does not lead anywhere.Check each segment; a common cause is forgetting the mod declaration entirely.
unused import warningYou brought in a name and never used it.Delete the use. Do not leave these; they hide the real imports.

Now make it stick: work through the drills for this module, then carry on to Module 11 — Generics.