🎓 A1Learner
🔍

Rust Modules

A module is a named group of related code inside a program. Modules also decide privacy by controlling what the rest of the program may see.

An inline module, called by its path

You may write the module inline, in the same file. Paths use :: between names — square, inside math. The function needs pub. Everything is private by default. Code outside the module cannot see an item until you write pub:

mod math {
    pub fn square(x: i32) -> i32 { x * x }
}
println!("{}", math::square(4));

crate:: starts at the very top

The same function, called by its full address from the root of your own crate:

println!("{}", crate::math::square(5));

Modules inside modules, super:: upwards

Modules can live inside modules. inner is the child, and outer is its parent. Modules side by side in one parent are siblings. super:: means the parent module — inner uses it to call outer's hello:

mod outer {
    pub fn hello() -> &'static str { "hi from outer" }
    pub mod inner {
        pub fn greet() -> String { format!("{}!", super::hello()) }
    }
}
println!("{}", outer::inner::greet());

mod name; loads the code from a file

More often the module lives in its own file, and the declaration alone loads it:

// in src/main.rs:
mod garden;
// Rust loads the garden code from src/garden.rs
// (or the older style: src/garden/mod.rs)

Example

mod math {
    pub fn square(x: i32) -> i32 { x * x }
    pub fn cube(x: i32) -> i32 { x * x * x }
}
fn main() {
    println!("{} {}", math::square(4), math::cube(3));
    println!("{}", crate::math::square(5));
}

Key points

  • A module keeps related code together under one name.
  • You can declare a submodule in any file, not only the root.
  • A mod line for vegetables inside src/garden.rs makes vegetables a child of garden.
  • If Rust "cannot find" your module, the root is the place to check.
  • One big file grows hard to search as a program grows.

In this example, math is an inline module holding two functions, square and cube. Both are marked pub, so main may use them. The first println! calls them by their path, math::square(4) and math::cube(3), printing 16 and 27. The second call, crate::math::square(5), spells the same address from the very top of the crate and prints 25. Same function, two ways to write its address — a short relative path, or the full path from the root.

Note

The module tree always starts at the crate root — src/main.rs for a program, src/lib.rs for a library.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Where does the module tree start?