How to structure a project with multiple files

Structure a Rust project by creating a src directory with main.rs as the entry point and using the mod keyword to declare additional module files.

Structure a multi-file Rust project by creating a src directory with a main.rs entry point and additional .rs files for modules, then declare them in main.rs using the mod keyword.

// src/main.rs
mod calculator;

fn main() {
    println!("Result: {}", calculator::add(2, 3));
}

// src/calculator.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
  1. Create the project directory and initialize it with Cargo. cargo new my_project && cd my_project

  2. Create the src directory if it doesn't exist and add your module file. mkdir -p src && touch src/calculator.rs

  3. Declare the module in src/main.rs using the mod keyword. mod calculator;

  4. Import and use the public items from the module in main.rs. use calculator::add;

  5. Build and run the project to verify the structure works. cargo run