Module Basics

Back

Loading concept...

๐Ÿ  Rust Modules: Building Your Code Mansion

Imagine youโ€™re building the biggest, coolest mansion ever. But hereโ€™s the thing โ€” you canโ€™t just throw all the furniture, toys, food, and clothes into ONE giant room! That would be chaos! ๐ŸŽข

Instead, you organize everything into rooms. The kitchen has cooking stuff. The bedroom has your bed. The playroom has your toys. Each room has a door โ€” some doors are open for everyone, and some are private (like your secret diary room ๐Ÿ”).

Thatโ€™s exactly what Rust modules are! Theyโ€™re rooms in your code mansion that keep everything organized and tidy.


๐Ÿงฑ What is a Module?

A module is like a room in your house. Itโ€™s a container that holds related code together.

Think about it:

  • ๐Ÿณ Kitchen โ†’ cooking functions
  • ๐Ÿ›๏ธ Bedroom โ†’ sleeping functions
  • ๐ŸŽฎ Playroom โ†’ game functions

In Rust, we create a โ€œroomโ€ using the mod keyword:

mod kitchen {
    fn cook_pasta() {
        println!("Cooking!");
    }
}

Thatโ€™s it! You just built a kitchen room with a cooking function inside!


๐Ÿ“ Module File Structure

Now, imagine your mansion gets SO big that you canโ€™t fit everything on one blueprint. You need separate blueprints for each room!

Rust gives you two ways to organize modules in files:

Way 1: Room Inside the Main File

Put everything in one file (like a small apartment):

// main.rs
mod kitchen {
    pub fn cook() {}
}

mod bedroom {
    pub fn sleep() {}
}

Way 2: Separate Files for Each Room

Each room gets its own file (like a real mansion):

my_project/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.rs
โ”‚   โ”œโ”€โ”€ kitchen.rs
โ”‚   โ””โ”€โ”€ bedroom.rs

In main.rs, you just announce the rooms exist:

mod kitchen;  // Rust looks for
              // kitchen.rs
mod bedroom;  // Rust looks for
              // bedroom.rs

Way 3: Folders for Big Rooms

Super big rooms get their own folder with a special mod.rs file:

src/
โ”œโ”€โ”€ main.rs
โ””โ”€โ”€ kitchen/
    โ”œโ”€โ”€ mod.rs
    โ””โ”€โ”€ oven.rs

๐Ÿ›ค๏ธ Paths: Finding Your Way

Imagine youโ€™re in the living room and want something from the kitchen. You need directions!

In Rust, paths are like addresses to find things in your code mansion.

Two Types of Paths:

๐Ÿ  Absolute Path โ€” Start from the front door:

crate::kitchen::cook_pasta();
// "From the main entrance,
//  go to kitchen,
//  find cook_pasta"

๐Ÿ‘ฃ Relative Path โ€” Start from where you are:

kitchen::cook_pasta();
// "From here, go to kitchen,
//  find cook_pasta"

The super Keyword

super means โ€œgo to the parent roomโ€ (like going upstairs):

mod kitchen {
    mod pantry {
        fn get_ingredient() {
            super::cook();
            // Go up to kitchen,
            // then call cook()
        }
    }
    fn cook() {}
}

๐Ÿ”“ The pub Keyword: Open or Locked Doors

By default, every room in Rust has a locked door. Nobody outside can peek in!

To open the door, use pub:

mod kitchen {
    pub fn cook() {
        // Anyone can use this!
    }

    fn secret_recipe() {
        // Private! Only kitchen
        // code can use this
    }
}

Making Parts Public

You can make different things public:

pub mod kitchen {      // Public room
    pub fn cook() {}   // Public function
    pub struct Oven {  // Public struct
        pub temp: i32, // Public field
    }
}

๐ŸŽญ Visibility Modifiers: Who Can Enter?

Rust has special โ€œaccess passesโ€ for different levels of privacy:

Modifier Who Can Access?
(nothing) Only same room
pub Everyone, anywhere
pub(crate) Only this mansion
pub(super) This room + parent
pub(in path) Specific rooms only

Example:

mod house {
    pub(crate) fn family_only() {
        // Only code in this
        // project can call me
    }

    mod bedroom {
        pub(super) fn wake_up() {
            // Only bedroom and
            // house can call me
        }
    }
}

Think of it like:

  • pub = Front door (anyone can enter)
  • pub(crate) = Family members only
  • pub(super) = This room + parents

๐Ÿ“ฆ The use Keyword: Creating Shortcuts

Imagine saying the full address every time:

โ€œHey, go to main mansion, then kitchen wing, then cooking area, then get the pasta maker!โ€

Exhausting! ๐Ÿ˜ซ

The use keyword creates a shortcut:

// Without shortcut:
crate::kitchen::cooking::make_pasta();
crate::kitchen::cooking::make_pizza();

// Create a shortcut!
use crate::kitchen::cooking;

// Now just say:
cooking::make_pasta();
cooking::make_pizza();

Bring It All the Way In:

use crate::kitchen::cooking::make_pasta;

// Now just:
make_pasta();

Multiple Shortcuts at Once:

use crate::kitchen::{
    make_pasta,
    make_pizza,
    make_salad
};

The Star Shortcut:

use crate::kitchen::*;
// Brings EVERYTHING from
// kitchen (use carefully!)

๐Ÿท๏ธ The as Keyword: Nicknames!

What if two things have the same name? Like two friends both named โ€œMaxโ€?

Give them nicknames with as:

use std::fmt::Result;
use std::io::Result as IoResult;

fn do_stuff() -> Result {
    // This is fmt::Result
    Ok(())
}

fn read_file() -> IoResult<String> {
    // This is io::Result
    Ok(String::new())
}

Another example:

use crate::kitchen::Oven
    as KitchenOven;
use crate::bakery::Oven
    as BakeryOven;

// Now no confusion!
let home = KitchenOven::new();
let shop = BakeryOven::new();

๐ŸŽฏ Putting It All Together

Letโ€™s build a mini mansion!

src/
โ”œโ”€โ”€ main.rs
โ”œโ”€โ”€ kitchen.rs
โ””โ”€โ”€ games/
    โ”œโ”€โ”€ mod.rs
    โ””โ”€โ”€ cards.rs

main.rs:

mod kitchen;
mod games;

use kitchen::cook_dinner;
use games::cards::play_uno;

fn main() {
    cook_dinner();
    play_uno();
}

kitchen.rs:

pub fn cook_dinner() {
    println!("Dinner ready!");
}

fn secret_recipe() {
    // Private helper
}

games/mod.rs:

pub mod cards;

games/cards.rs:

pub fn play_uno() {
    println!("UNO!");
}

๐ŸŒŸ Quick Mental Map

graph TD A["crate - Your Mansion"] --> B["mod kitchen"] A --> C["mod bedroom"] A --> D["mod games"] D --> E["mod cards"] D --> F["mod board"] style A fill:#667eea style B fill:#4ECDC4 style C fill:#4ECDC4 style D fill:#FF6B6B style E fill:#FFE66D style F fill:#FFE66D

๐Ÿ’ก Remember These Magic Words!

Word What It Does
mod Creates a room
pub Opens the door
use Creates a shortcut
as Gives a nickname
super Go to parent room
crate The whole mansion

๐Ÿš€ You Did It!

You now understand how to:

  • โœ… Create modules (rooms)
  • โœ… Organize files (blueprints)
  • โœ… Navigate with paths (addresses)
  • โœ… Control access with pub (doors)
  • โœ… Use visibility modifiers (access passes)
  • โœ… Create shortcuts with use
  • โœ… Rename with as (nicknames)

Your Rust code mansion is ready to grow! ๐Ÿฐ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.