liveBook · Manning

Module

As explained in Learn Rust in a Month of Lunches

A module is a distinct, bounded software unit that groups related code or functionality and provides an organizational or interaction boundary within a larger system.

A Rust module is a named space for related functions, structs, and other code. Modules help organize growing programs, distinguish names that might otherwise conflict, and make code easier to read. section 14.1

Modules also control access:

  • Items inside a module are private by default. Add `pub` to make a function or module accessible from outside its private scope. section 14.1
  • A module can contain child modules. Child modules can use items in their parent, while `crate::` starts a path at the crate root and `super::` moves up one module. section 14.1.3
mod print_things {
    use std::fmt::Display;
 
    pub fn prints_one_thing<T: Display>(input: T) {
        println!("{}", input)
    }
}
 
fn main() {
    use print_things::prints_one_thing;
 
    prints_one_thing(6);
    prints_one_thing("Trying to print a string...".to_string());
}

This example makes a printing function public, imports it into `main`, and calls it with a number and a string. section 14.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines modules and works through `mod`, `pub`, nested modules, and paths; file organization is only briefly introduced.
Examples
Uses a printing module and nested country, province, and city modules.
What you can do after
Apply Rust's `mod`, `pub`, and module paths to organize code and control access.
How it connects
Connects modules to crates, namespaces, encapsulation, privacy, and path resolution.

Also explained in

Compare how 35 books explain module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.