Packages
Using and creating Cargo packages.
Intermediateā±ļø 35 minš Prerequisites: 1
Packages
A package consists of one or more crates that together provide a functionality.
Package Structure
my_project/
āāā Cargo.toml
āāā src/
āāā main.rs
Binary Crate
RUST// src/main.rs fn main() { println!("Hello, world!"); }
Library Crate
RUST// src/lib.rs pub fn add(left: u64, right: u64) -> u64 { left + right }
Cargo.toml
TOML[package] name = "my_project" version = "0.1.0" edition = "2021" [dependencies]
Adding Dependencies
TOML[dependencies] serde = "1.0" rand = "0.8"
Workspace
TOML[workspace] members = [ "adder", "add_one", ]
Public API
RUST// src/lib.rs pub mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub use crate::front_of_house::hosting;
Code Examples
Cargo.toml
Package configuration
RUST
# Cargo.toml
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"
[dependencies]
# Dependencies go hereExplanation:
The Cargo.toml file contains package metadata and dependencies. name, version, and edition are required fields.
Binary Crate
Creating an executable program
RUST
fn main() {
println!("Hello from binary crate!");
let result = my_lib::add(5, 3);
println!("5 + 3 = {}", result);
}
pub mod my_lib {
pub fn add(x: i32, y: i32) -> i32 {
x + y
}
}Explanation:
A binary crate is an executable program. main.rs contains the main() function. lib.rs defines a library crate.
Dependencies
Using external crates
RUST
# Cargo.toml
[dependencies]
rand = "0.8"
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let number: u32 = rng.gen_range(1..=100);
println!("Random number: {}", number);
}Explanation:
In the Cargo.toml [dependencies] section, we can add external crates. cargo build automatically downloads and compiles them.
Exercises
Creating a Package
Create a new Cargo project!
Starter Code:
RUST
# Cargo.toml
# Write the package configuration
# src/main.rs
# Write the main function