Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 132 ยท Modules, Packages and Macros

Modules

Learn Rust modules: mod blocks, pub and private items, pub(crate) and pub(super), use, as, glob and nested imports, crate/self/super paths and re-exports.

A small program fits in one file. A real program has hundreds of functions and types, and somebody has to decide which of them belong together, which are safe to call from anywhere, and which are implementation details that nobody outside should touch. In Rust, modules answer all three questions. A module groups related items under a name, makes that name part of a path (geometry::area), and controls visibility: by default everything inside a module is private to it.

That default is the most important thing to learn here. In many languages you hide things by marking them private. In Rust you hide things by writing nothing, and you expose them by writing pub. The result is that a module's public surface is small, deliberate and visible at a glance. This lesson covers declaring modules, paths, the visibility keywords including pub(crate) and pub(super), bringing names into scope with use, re-exporting with pub use, and how modules map onto files. Everything runnable here uses inline mod blocks, because our editor compiles a single file; the file layout is shown in read-only snippets.

Declaring a module

A module is declared with the mod keyword and a block. Inside it you can put anything you can put at the top level of a file: functions, structs, enums, constants, traits, other modules.

Rust A first module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

To call something in a module you write its path, with :: between the names: greetings::english(). The functions marked pub are reachable from main; secret is not, but reveal (which lives in the same module) may call it freely. The module tree for this program has a hidden root, the crate root, with greetings and main as children.

Privacy: private by default

What happens if you reach for a private item from outside?

Rust Calling a private function (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc stops with E0603 ("function internal_audit is private"), points at the call with the label "private function", and adds a note showing where the function is defined. The fix is to add pub if the function is meant to be part of the module's interface, or to leave it and call something public instead. The privacy rule is precise: an item is visible to the module where it is defined and to all modules nested inside that module. Parents cannot see into children's private items, but children can see the private items of their ancestors.

Private fields protect invariants

The same rule applies to fields of a pub struct. Making the struct public does not make its fields public; each field needs its own pub. This is how you build types whose invariants cannot be broken from outside:

Rust A struct that guards its own rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because degrees is private and the only way to build a Celsius is Celsius::new, every Celsius in the program is guaranteed valid. If main tried Celsius { degrees: -1000.0 } or t.degrees = -1000.0, rustc would reject it with error[E0451] (private field in a struct literal) or error[E0616] (field is private). Keeping fields private and exposing methods is the standard way to make illegal states unrepresentable. (The same does not apply to enum variants: all variants of a pub enum are public automatically, as are all their fields.)

Paths: crate, self and super

A path says where an item lives. It can be:

  • Absolute, starting at the crate root with the keyword crate: crate::shapes::circle::area.
  • Relative to the current module, starting with a name in scope or with self: self::helper.
  • Relative to the parent, starting with super: super::helper. You can chain it: super::super::x.
Rust crate, self and super paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The nested module circle reaches shapes::pi, a private function of its parent, with super::pi(). That is allowed precisely because of the rule above: children can see the private items of their ancestors.

Finer visibility: pub(crate), pub(super), pub(in path)

pub alone means "visible everywhere the module itself is reachable". Sometimes that is too much. You can narrow it:

Written Visible in
(nothing) the current module and its descendants
pub(self) the same as nothing
pub(super) the parent module (and everything inside it)
pub(crate) the whole current crate, but not other crates
pub(in crate::a::b) the given ancestor module
pub everywhere the item can be named

pub(crate) is the workhorse. In a library crate it means "usable by any code in this library but not part of the public API", which is exactly what you want for internal helpers shared between modules. pub(super) is handy for a submodule that provides something only for its parent.

Rust Choosing how far an item is visible

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The commented-out call fails because pub(super) makes assemble visible only inside engine, and main is outside. A single-file program has only one crate, so pub(crate) and pub behave identically here, but in a library the difference is the boundary of your public API.

Start every item private. Add pub(super) or pub(crate) when another module needs it, and pub only for what you want to promise to the outside world. Widening visibility later is a compatible change; narrowing it breaks users.

Bringing names into scope with use

Writing crate::shapes::circle::area every time is tiring. The use declaration creates a short name for a path in the current scope:

Rust use, as, nested and glob imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A few conventions are worth memorizing because they make code easy to read:

  • Functions: import the parent module, not the function (use std::fs; then fs::read_to_string(...)), so the reader sees where it comes from. The exception is very common functions in your own module.
  • Types, traits and enums: import the item itself (use std::collections::HashMap;).
  • Name clashes: import the parents (fmt::Result vs io::Result) or rename with as.
  • Nested paths (use std::{fs, io::{self, Read}};) keep one import line per crate. self inside the braces means the module itself.
  • Glob imports (use some::module::*;) pull in every public name. They are fine in tests (use super::*;) and for a prelude, but avoid them elsewhere: the reader cannot tell where a name came from, and a new item in the source module may silently clash with yours.

One more surprising rule: a module does not inherit its parent's use declarations. Each module has its own scope, so a nested module that wants HashMap needs its own use std::collections::HashMap;, or use super::*;.

Rust A nested module needs its own imports (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc reports E0425 ("cannot find type HashMap in this scope") at the return type and E0433 at the HashMap::new() call, and suggests importing std::collections::HashMap inside the module. It also warns that the import at the top is unused, which is the giveaway: that use only affects the crate root. The fix is to write use std::collections::HashMap; inside inventory, or use super::HashMap;.

Re-exports with pub use

use makes a name available for you. pub use makes it available to everyone who can see your module, as if it were declared there. This lets you organize code internally however you like and present a flat, tidy interface outside. It is how crates hide their internal layout.

Rust A facade built with pub use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The modules parsing and math are private, so outside code cannot name them at all, yet the two functions they contain are reachable under library::. The authors can later move dot to a different internal module, and nobody's code breaks. The standard library itself does this constantly: std::collections::HashMap is defined deep inside std::collections::hash::map.

The same trick is how a prelude works: a module such as prelude that pub uses the handful of items most users need, so they can write use mycrate::prelude::*;.

Modules and files

Real projects split modules across files, because a file per module keeps each one small. The rule is that mod name; (with a semicolon instead of a block) tells the compiler to load the module's contents from a file. The name decides which file:

TEXT
my_app/
โ”œโ”€โ”€ Cargo.toml
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main.rs            // crate root: declares `mod shapes;` and `mod util;`
    โ”œโ”€โ”€ shapes.rs          // contents of `mod shapes`
    โ”œโ”€โ”€ shapes/
    โ”‚   โ””โ”€โ”€ circle.rs      // contents of `mod circle` inside `shapes`
    โ””โ”€โ”€ util.rs
Rust
// Read-only: src/main.rs in a Cargo project
mod shapes;   // loads src/shapes.rs
mod util;     // loads src/util.rs

fn main() {
    println!("{}", shapes::circle::area(1.0));
}
Rust
// Read-only: src/shapes.rs
pub mod circle;  // loads src/shapes/circle.rs

pub fn unit() -> f64 {
    1.0
}
Rust
// Read-only: src/shapes/circle.rs
pub fn area(radius: f64) -> f64 {
    std::f64::consts::PI * radius * radius
}

Two points trip people up. First, the module tree is built from mod declarations, not from the file system: a file that no mod line mentions is simply not part of the program. Second, there is an older layout, shapes/mod.rs instead of shapes.rs plus a shapes/ folder; it still works but the modern layout avoids a dozen files all named mod.rs. Use one style consistently.

A library crate's root is src/lib.rs, and the same mod and pub use rules apply; you will meet it in crates and dependencies. Tests usually live in a child module mod tests marked #[cfg(test)], which starts with use super::*; to see everything in the module it tests (see attributes and cfg).

Design guidance

  • One idea per module. If you cannot name a module in one or two words, it is probably doing too much.
  • Prefer a shallow tree. Paths like a::b::c::d::item mean readers must remember a lot.
  • Expose a small public surface and hide the rest. It is easier to open things up than to take them away.
  • Put the main type in the module named after it, and pub use it at the parent, so users write shapes::Circle rather than shapes::circle::Circle.
  • Do not make everything pub "to be safe". A pub item is a promise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default visibility of an item (function, struct, constant) declared inside a module?

    Everything is private unless you write pub (or a restricted form like pub(crate)).
  2. 2. In a nested module, which path reaches a function helper in the parent module?

    super means the parent module. self is the current one, and crate is the root, which may or may not be the parent.
  3. 3. You make a struct pub but write its field as name: String without pub. Who can read the field directly?

    Field visibility is separate from the struct's. A private field is accessible in the defining module, including the struct's impl blocks there.
  4. 4. What does pub(crate) mean?

    pub(crate) is for items shared across modules inside one crate that should not be part of its public API.
  5. 5. What does pub use self::math::dot; do inside a module?

    A re-export lets you present a clean public path while keeping the real definition elsewhere.

Summary

  • mod name { ... } groups items; paths use :: and start at crate, self, super or a name in scope.
  • Everything is private by default; pub exposes an item, and pub(crate), pub(super) and pub(in path) narrow how far.
  • Private items are visible in the module that defines them and in its descendants; fields have their own visibility, which is how types protect their invariants.
  • use creates shorter names, with as for renaming, braces for nested imports and * for globs (use sparingly); modules do not inherit their parent's imports.
  • pub use re-exports, letting you separate internal layout from the public interface.
  • mod name; loads a module from name.rs (or name/mod.rs); the module tree comes from mod declarations, not from folders.

Next: Crates, Dependencies and Features