liveBook · Manning

Mod keyword

As explained in Refactoring to Rust

A mod statement is Rust syntax that declares a module and directs the compiler to its source definition.

The mod keyword declares a Rust module, groups related code, and tells the compiler how to find that module’s definition. A module can use block syntax, mod input { ... }, or file syntax, mod input;, which loads input.rs. section 5.1 section 5.1.2

Move greeting code into modules

A greeting program can declare mod input; and mod output; in main.rs, then place public functions in input.rs and output.rs. Import them with use input::get_name and use output::{goodbye, hello}. The program retains its original behavior while separating input and output responsibilities. section 5.1 section 5.1.2

When organizing code with mod:

  • Use mod name { ... } to keep a module’s contents in the current file. section 5.4
  • Use mod name; to place the definition in name.rs; nested modules require corresponding parent declarations. section 5.1.2
  • Mark functions, enums, or other items pub when other modules must access them; items are private by default. section 5.1
  • Use relative or absolute paths to reach items, with crate referring to the current crate root. section 5.4
Listing 5.1 Code to get a user’s name and greet them
use std::io::stdin;

fn main() {
  let name = get_name();

  hello(&name);
  goodbye(&name);
}

fn get_name() -> String {
  let mut name = String::new();

  println!("Please enter your name");
  stdin().read_line(&mut name).unwrap();  #1

  name
}

fn goodbye(name: &str) {
  println!("Goodbye, {}", name);
}

fn hello(name: &str) {
  println!("Hello, {}", name);
}

Inspect the complete greeting program before modularization, then compare its functions with the separated input and output modules. section 5.1

How Refactoring to Rust covers it

How deep it goes
Explains inline and file modules, visibility, nesting, and paths, but stops short of broader module-system internals.
Examples
Uses a greeting program split into input.rs, output.rs, and day_kind.rs, including compiler errors and corrected imports.
What it assumes
Assumes basic Rust functions and program structure while teaching namespaces, imports, privacy, and crate-root paths through errors.
What you can do after
Apply it to split a Rust program into focused inline or file-based modules while preserving access through imports and visibility.
How it connects
Connects modules with use statements, pub visibility, namespaces, crates, and relative or absolute paths.

Related concepts

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