How to Split a Crate into Multiple Files

Split a Rust crate by creating a lib.rs root and declaring separate module files to organize code logically.

Split a Rust crate into multiple files by creating a src/lib.rs for library code and moving logic into separate modules within src/.

  1. Create a new file named src/lib.rs to serve as the library root.
  2. Move your shared logic into src/lib.rs and define public items with pub.
  3. Create a new file for each logical module, such as src/utils.rs.
  4. Declare the module in src/lib.rs using mod utils;.
  5. Import the module's items into scope with pub use utils::*;.
  6. Update Cargo.toml to 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");
}