- dependencies
- path
Crate library and use local library
- Create a library:
cargo new add-lib --lib
The files created:
examples/libraries/add-lib/Cargo.toml
[package] name = "add-lib" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies]
examples/libraries/add-lib/src/lib.rs
pub fn add(left: usize, right: usize) -> usize { left + right } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let result = add(2, 2); assert_eq!(result, 4); } }
- Create another crate that will use this library:
cargo new add-app cd add-app cargo add --path ../add-lib/
examples/libraries/add-app/Cargo.toml
[package] name = "add-app" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] add-lib = { version = "0.1.0", path = "../add-lib" }
examples/libraries/add-app/src/main.rs
//cargo add --path ../add-lib/ fn main() { println!("Using the add_lib crate: {}", add_lib::add(2, 3)); }