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
