Modules Exercises

Overview

These exercises cover Rust’s module system — organizing code with visibility control and re-exports.


modules1 - Public Functions

Concept: Using pub to make items visible outside a module

mod sausage_factory {
    fn get_secret_recipe() -> String {
        String::from("Ginger")  // Private — only accessible inside this module
    }
 
    pub fn make_sausage() {  // Public — accessible from outside
        get_secret_recipe();
        println!("sausage!");
    }
}
 
fn main() {
    sausage_factory::make_sausage();  // ✅ Works — make_sausage is public
    // sausage_factory::get_secret_recipe();  // ❌ Error — private function
}

Key Takeaways:

  • Items in modules are private by default
  • Add pub to make them accessible from outside
  • Private items can still be called from within the same module

modules2 - Re-exports with use and as

Concept: Bringing nested paths into scope and renaming them

mod delicious_snacks {
    // Re-export with pub use and alias with as
    pub use self::fruits::PEAR as fruit;
    pub use self::veggies::CUCUMBER as veggie;
 
    mod fruits {
        pub const PEAR: &str = "Pear";
        pub const APPLE: &str = "Apple";
    }
 
    mod veggies {
        pub const CUCUMBER: &str = "Cucumber";
        pub const CARROT: &str = "Carrot";
    }
}
 
fn main() {
    // Access via the re-exported aliases
    println!("favorite snacks: {} and {}",
        delicious_snacks::fruit,   // "Pear"
        delicious_snacks::veggie,  // "Cucumber"
    );
}

Key Takeaways:

  • use brings paths into scope
  • as creates an alias (different name)
  • pub use re-exports — makes the item accessible through the parent module
  • self:: refers to the current module

modules3 - Using Standard Library Modules

Concept: Importing from std with nested paths

use std::time::{SystemTime, UNIX_EPOCH};
 
fn main() {
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
    }
}

Key Takeaways:

  • Use curly braces {} to import multiple items from one path

  • std::time::{SystemTime, UNIX_EPOCH} is equivalent to:

    use std::time::SystemTime;
    use std::time::UNIX_EPOCH;
  • This is called a nested path or grouped import


Rust Book Reference