Module System In Rust

Raunak
Rustaceans

--

We all know why modules are important for a developer and what are its advantages, So today we’ll be studying about modules in rust.

  1. How are modules built in Rust
  2. How to import them in other places
  3. And lastly we’ll also understand the how it works internally.

A module in general is some collection of logical unit, that is managed separately. In rust-lang module is a collection of functions structs traits impl blocks and even other modules

In Rust modules are defined using the mod keyword followed module name and by-default they are private and to make them public you can use pub keyword

// private module
mod my_first_mod{
fn private_function() {
println!("called `my_mod::private_function()`");
}
}

// public module
pub mod my_second_module{
pub fn public_fn() {
println!("called `my_mod::public_function()`");
}
}

Modules can also be nested

pub mod my_first_mod{
// public module
pub mod my_second_module{
pub fn public_fn() {
println!("called `my_mod::public_function()`");
}
}
}

To import module at other places, we have use keyword to the rescue !! with the help of use and as keyword we can import modules and use them at ease.

// front_of_house.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}

// eat_at_res.rs
use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}

as we can see that add_to_waitlist is called from another file that is “eat_at_res.rs” on the 1st line we have used “use” keyword to import the “front_of_house.rs” module.

With “as” keyword things get little bit easier, because with “as” keyword we can rename the module in given scope, an example is shown below.

// eat_at_res.rs
use crate::front_of_house::hosting as hosting_module;

pub fn eat_at_restaurant() {
hosting_module::add_to_waitlist();
}

// front_of_house.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}

Lastly, we’ll see how modules in Rust are different from modules present in other languages, That is because the modules are not bound to the ‘File system,’ meaning they are independent of their file locations, allowing the code to reside anywhere.

But it is suggested to have specific files as per some programming patterns, even the Rust foundation saw its need and later started supported some patterns such as, rust will always search for a folder and file with .rs extension or module_name with .rs extension

--

--