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
}
-
Create the project directory and initialize it with Cargo.
cargo new my_project && cd my_project -
Create the
srcdirectory if it doesn't exist and add your module file.mkdir -p src && touch src/calculator.rs -
Declare the module in
src/main.rsusing themodkeyword.mod calculator; -
Import and use the public items from the module in
main.rs.use calculator::add; -
Build and run the project to verify the structure works.
cargo run