[Avg. reading time: 7 minutes]
Creating a Library Crate
So far you built binary crates (executables) using main.rs.
Rust also supports library crates, which are reusable packages that expose functions, structs, and modules for other projects to use.
- A binary crate starts at
src/main.rs - A library crate starts at
src/lib.rs
When you create a library crate, Cargo builds a .rlib (and other artifacts) that other crates can depend on.
Part 1: Create a Department library
To create a new library include –lib when creating a new cargo package
cargo new newlib --lib

departments.rs
pub mod dept {
fn get_number(num: i32) -> String {
match num {
1 => return "123-456-7890".to_string(),
2 => return "987-654-3210".to_string(),
_ => return "000-000-0000".to_string(),
}
}
pub mod sales {
pub fn meet_customer(num: i32) {
println!("Sales : meet customer {num}");
let phone_number = super::get_number(num);
println!("Sales calling {}", phone_number);
}
}
pub mod service {
pub fn meet_customer(num: i32) {
println!("Service : meet customer {num}");
let phone_number = super::get_number(num);
let ticket_number = self::get_service_ticket_number(num);
println!("Calling {phone_number} with ticket number {ticket_number}");
}
fn get_service_ticket_number(num: i32) -> i32 {
match num {
1 => return 2452423,
2 => return 2341332,
_ => return 6868765,
}
}
}
}
lib.rs
- lib.rs is the entry point for your library crate.
- It defines what modules are exposed to downstream crates.
pub mod departments;
Build the library
cargo build
this gives you:
- A compiled library crate named newlib
- Other projects can now import it using use newlib::…
Part 2: Use the above library
cargo new newlib-test
cargo.toml
[dependencies]
newlib = {path = "../newlib"}
or
cargo add newlib --path ../newlib
If its common library across team (Private)
cargo add newlib --git https://github.com/user/newlib
main.rs
use newlib::departments::dept;
fn main() {
dept::sales::meet_customer(1);
dept::service::meet_customer(3);
}
cargo run
Summary
- lib.rs defines the public API surface of a library crate
- A library crate is imported using the crate name (newlib::…)
- pub mod departments; in lib.rs exposes departments.rs
- Inside modules, helpers stay private unless you mark them pub