Modules can be used to separate scopes for organizing code.

Modules can be nested

Importing items

Use use

mod cake {
  pub mod flavors {
    pub const COCONUT: &str = "Coconut";
  }
}
 
// A module must be `pub` to access it by name.
use cake::flavors;
 
println!("{}", flavors::COCONUT);

We can also rename imports:

use i32 as Integer;
 
let number: Integer = 137;

Exporting items

When our crate is a library, anyone can access public modules. To make a module only accessible internally by the crate, and not to users of the library, we use pub(crate)

pub(crate) fn print_lemon() -> {
  println!("Lemon");
}

Separate files

To use a module in separate file, consider the example below on src/cake.rs

mod cake;
 
fn main() {
  let guess = "Lady Baltimore";
 
  if cake::is_favorite(guess) {
    println!("That's my favorite cake!");
  } else {
    println!("Not my favorite, but still delicious.");
  }
}
 

We can access the module within the same folder, e.g., src/main.rs by using use cake;

For different folder, we can add mod.rs in the folder. mod.rs will be treated as a “file” for the folder, to bridge the insides of the folder and the files 1 level up the folder.

  • To access modules from the root of our project, we can use crate::.
  • To access the relative parent module, we can use super::.
  • To access the current module, we can also use self::.