Split modules across files by creating a new file for the module and declaring it with mod in the parent file.
- Create a new file named
my_module.rsin the same directory as yourmain.rs. - Add
mod my_module;to yourmain.rsto declare the module. - Define your items inside
my_module.rsand access them usingmy_module::item_nameinmain.rs.
// main.rs
mod my_module;
fn main() {
my_module::greet();
}
// my_module.rs
pub fn greet() {
println!("Hello from a separate file!");
}