rustlayoutmodule

How to add a common module to examples in Rust?


I have 2 binaries in examples folder: example1_main.rs, example2_main.rs. How do I add a common module example_common.rs that could be used by all example programs? and how to import them?

The files layout is like this:

src: ...
examples
|- example1_main.rs
|- example2_main.rs
|- example_common1.rs (how to add common modules and import them in *_main.rs?)
|- example_common2.rs

Solution

  • You can use the include! macro, which copies the source code, instead of a normal use statement:

    // examples/example_main.rs
    
    include!("./common.rs");
    
    pub fn main() {
        println!("{}", library::add(common::double(2), 2)); // 6
    }
    
    // examples/common.rs
    
    mod common {
        pub fn double(x: u64) -> u64 {
            x * 2
        }
    }
    
    // src/lib.rs
    
    pub fn add(left: u64, right: u64) -> u64 {
        left + right
    }