Day 21: Modules
MediumModulespubuse+1

Day 21: Modules

Modules help organize code into logical units with controlled visibility.

Defining Modules

mod garden {
    pub mod vegetables {
        pub fn plant() {
            println!("Planting vegetables!");
        }
    }
    
    fn private_helper() {
        // Only accessible within garden module
    }
}

Visibility Rules

KeywordVisibility
(none)Private to current module
pubPublic
pub(crate)Public within crate
pub(super)Public to parent module

In Rust, everything is private by default! You must explicitly mark items as pub to make them accessible.

Using Items

// Absolute path
crate::garden::vegetables::plant();

// Relative path
garden::vegetables::plant();

// With use statement
use garden::vegetables::plant;
plant();

The super Keyword

Access parent module:

mod parent {
    pub fn helper() -> i32 { 42 }
    
    mod child {
        pub fn use_parent() -> i32 {
            super::helper()  // Access parent's function
        }
    }
}

File-Based Modules

src/
├── main.rs
├── garden.rs           // mod garden
└── garden/
    └── vegetables.rs   // mod garden::vegetables

The Task

Fix the module visibility:

  1. Make math::add public
  2. Make math::advanced::multiply_and_add public
  3. Use super::add in multiply_and_add

Requirements

  • math::add(5, 3)8
  • math::advanced::multiply_and_add(2, 3, 4)10 (2*3 + 4)

Hints

mod math {
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    pub mod advanced {
        pub fn multiply_and_add(a: i32, b: i32, c: i32) -> i32 {
            super::add(a * b, c)
        }
    }
}
Language: Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output
Run to see the result here.
    Day 21: Modules · RUST Challenge | learn.sol