🎓 A1Learner
🔍

Rust Modules Basics

A module is a named group of code inside a project. Modules keep a project's names tidy as the code grows.

A module groups related code

The word mod opens a named group. Code outside reaches in through the group name and ::

mod kitchen {
    pub fn greet() {
        println!("welcome to the kitchen");
    }
}

fn main() {
    kitchen::greet();
}

pub opens an item to the outside

Items start out private. hint can call the private secret, because both live in the same module. A call to kitchen::secret() from main would not compile:

mod kitchen {
    pub fn menu() {
        println!("soup of the day");
    }

    fn secret() -> &'static str {
        "a pinch of salt"
    }

    pub fn hint() {
        println!("the secret is {}", secret());
    }
}

fn main() {
    kitchen::menu();
    kitchen::hint();
}

use writes a long path once

std::collections::HashMap is a long path to write at every mention. A use line brings the short name into reach:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("ada", 10);
    scores.insert("bo", 7);
    println!("ada = {}", scores["ada"]);
}

Modules can nest

A module can hold another module. The path just grows by one name and one :: at a time:

mod house {
    pub mod kitchen {
        pub fn greet() {
            println!("from the kitchen");
        }
    }
}

fn main() {
    house::kitchen::greet();
}

Example

mod scores {
    pub fn report(name: &str, points: i32) {
        println!("{} scored {}", name, points);
    }
}

use std::collections::HashMap;

fn main() {
    let mut table = HashMap::new();
    table.insert("ada", 10);
    table.insert("bo", 7);
    scores::report("ada", table["ada"]);
    scores::report("bo", table["bo"]);
}

Key points

  • An item inside a module is reached by its path, like kitchen::greet.
  • Items in a module are private until the word pub marks them.
  • Use use to write a long path once.
  • After the use line, the short name alone is enough.
  • A crate is the whole project, and all its modules compile together as one.

In this example, the scores module holds one public function, report. main builds a HashMap of names and scores. The use line at the top brings HashMap's short name into reach. Each report call walks the path scores::report. The module keeps the printing code in one named place, away from main. Rust Modules, in the Intermediate course, goes deeper from here — modules split across files, and the full rules for what outside code may see.

Note

Privacy in Rust belongs to modules, not classes.

Code in the same module can see the module's private items.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does pub do to a function inside a module?