Module 8 • Lesson 41

Organizing Code with Modules

📚 8 min💻 Free🦀 nixus.pro

Modules: Organizing Code

// src/main.rs or src/lib.rs

mod math {
    // Private by default
    fn helper() -> i32 { 42 }

    // pub to make accessible outside module
    pub fn add(a: i32, b: i32) -> i32 { a + b }
    pub fn subtract(a: i32, b: i32) -> i32 { a - b }

    pub mod advanced {
        pub fn square(x: i32) -> i32 { x * x }
        pub fn cube(x: i32) -> i32 { x * x * x }
    }
}

mod geometry {
    pub struct Point {
        pub x: f64,
        pub y: f64,
        secret: f64, // Private field
    }

    impl Point {
        pub fn new(x: f64, y: f64) -> Self {
            Point { x, y, secret: 0.0 }
        }
        pub fn distance_to(&self, other: &Point) -> f64 {
            ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
        }
    }
}

fn main() {
    // Full path
    println!("{}", math::add(2, 3));
    println!("{}", math::advanced::square(4));

    // Struct with pub fields
    let p = geometry::Point::new(0.0, 0.0);
    println!("x={}", p.x); // Fine - pub field
    // p.secret  // ERROR: private field
}

Module Files

// src/
//   main.rs
//   lib.rs
//   math.rs         <- mod math; in lib.rs
//   geometry/
//     mod.rs        <- mod geometry; in lib.rs
//     shapes.rs     <- pub mod shapes; in mod.rs

// lib.rs:
// pub mod math;
// pub mod geometry;

// math.rs:
// pub fn add(a: i32, b: i32) -> i32 { a + b }

// geometry/mod.rs:
// pub mod shapes;
// pub use shapes::Circle; // Re-export

// Access:
// use mylib::math::add;
// use mylib::geometry::shapes::Circle;

🎯 Practice

  1. Create a library crate with modules: auth (login, logout functions), data (save, load functions)
  2. Make some items public, some private, and verify the access control
  3. Use pub use to re-export an internal item at a higher level

🎉 Key Takeaways