Split a Rust crate into multiple files by creating a src/lib.rs for library code and moving logic into separate modules within src/.
- Create a new file named
src/lib.rsto serve as the library root. - Move your shared logic into
src/lib.rsand define public items withpub. - Create a new file for each logical module, such as
src/utils.rs. - Declare the module in
src/lib.rsusingmod utils;. - Import the module's items into scope with
pub use utils::*;. - Update
Cargo.tomlto include[lib]if you are building a library crate.
// src/lib.rs
mod utils;
pub use utils::helper_function;
pub fn main_logic() {
helper_function();
}
// src/utils.rs
pub fn helper_function() {
println!("Helper logic here");
}