RRust By Example
intermediateModules

Module Re-exports

Re-export items with pub use for cleaner APIs.

Module Re-exports

Re-export items with pub use for cleaner APIs.

Difficulty

Intermediate

Code

rust
mod shapes {
    pub mod circle {
        pub fn area(radius: f64) -> f64 {
            std::f64::consts::PI * radius * radius
        }
    }

    pub mod rectangle {
        pub fn area(width: f64, height: f64) -> f64 {
            width * height
        }
    }

    // re-export for convenience
    pub use circle::area as circle_area;
    pub use rectangle::area as rect_area;
}

fn main() {
    // use full path
    println!("circle: {}", shapes::circle::area(5.0));

    // use re-exported names
    println!("circle: {}", shapes::circle_area(5.0));
    println!("rect: {}", shapes::rect_area(4.0, 6.0));
}

Explanation

pub use re-exports items for flat APIs.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the modules category to build a complete understanding of this topic.

More Modules Examples