Rust modules

Rust includes a module system for grouping code into logical groups, which may include structs, implementations, other modules etc. Module also give us the ability to manage module code’s visibility.

There’s a couple of ways for declaring our modules.

Option 1

Assuming we’ve used cargo init to create our project or simply laid out our code in the same way, then we’ll have a src folder and within that we’ll create a folder named math which will become our module name. Within math we add a file named mod.rs

src
  |--- math
    |--- mod.rs
  |--- main.rs

So here’s a very basic mod.rs file

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

and here’s the main.rs file

mod math;

fn main() {
    println!("{}", math::add(1, 2));
}

Option 2

The second option is to name the module file math.rs and this is stored at the same level as the main.rs file, i.e.

src
  |--- math.rs
  |--- main.rs

Nested Modules

We can also nest modules (modules within modules), for example

pub mod nested {
  pub fn add(a: i32, b: i32) -> i32 {
    a + b
  }
}

// in use 

mod math;

fn main() {
    println!("{}", math::nested::add(1, 2));
}