Crates
Using and publishing crates.
Intermediate⏱️ 40 min📚 Prerequisites: 1
Crates
A crate is the smallest compilation unit in Rust. There are two types:
- Binary crate: Executable program
- Library crate: Reusable code
Crate Types
Binary Crate
RUST// src/main.rs fn main() { println!("Hello, world!"); }
Library Crate
RUST// src/lib.rs pub fn greet() { println!("Hello from library!"); }
Using Crates
RUST// In another crate use my_crate::greet; greet();
Public API
RUST// src/lib.rs pub mod utils { pub fn helper() {} fn private_helper() {} // Not public } pub use utils::helper; // Re-export
Publishing to crates.io
TOML# Cargo.toml [package] name = "my_crate" version = "0.1.0" edition = "2021" license = "MIT" description = "A useful crate" [dependencies]
BASHcargo publish
Documentation
RUST/// This is a function that adds two numbers. /// /// # Example /// /// ``` /// let result = add(2, 3); /// assert_eq!(result, 5); /// ``` pub fn add(a: i32, b: i32) -> i32 { a + b }
Code Examples
Library Crate
Creating a library crate
RUST
pub mod math {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
pub fn multiply(x: i32, y: i32) -> i32 {
x * y
}
}
use my_crate::math;
fn main() {
let sum = math::add(5, 3);
println!("Sum: {}", sum);
}Explanation:
A library crate (lib.rs) contains reusable code. The pub keyword makes it available to other crates.
Documentation
Writing documentation
RUST
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Explanation:
The /// comments generate documentation. The cargo doc command creates HTML documentation. The ``` code blocks contain examples.
Re-export
Re-exporting public API
RUST
mod internal {
pub fn helper() {
println!("Helper function");
}
}
pub use internal::helper;
use my_crate::helper;
fn main() {
helper();
}Explanation:
pub use allows us to make an internal module function directly accessible in the crate API. This results in a simpler API.
Exercises
Library Crate
Create a library crate with math functions!