Rust Crates

Packages and dependencies in Rust

📦 What are Rust Crates?

Crates are Rust's compilation units and packages. They contain libraries or executables that can be shared and reused. Think of them as building blocks for Rust applications and the ecosystem's foundation.


// Using an external crate
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u32,
}
                                    

Types of Crates

⚙️

Binary Crates

Executable programs with main()

// src/main.rs
fn main() {
    println!("Hello, world!");
}
📚

Library Crates

Reusable code for other projects

// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
🌐

External Crates

Third-party packages from crates.io

[dependencies]
serde = "1.0"
tokio = "1.0"
🏠

Local Crates

Your own project crates

[dependencies]
my_utils = { path = "../utils" }

🔹 Creating a New Crate

Use Cargo to create new crates:

Commands:

  • cargo new my_project - Creates binary crate
  • cargo new my_lib --lib - Creates library crate
  • cargo build - Compiles the crate
  • cargo run - Runs binary crate
# Cargo.toml - Project configuration
[package]
name = "my_calculator"
version = "0.1.0"
edition = "2021"

[dependencies]
# External dependencies go here

🔹 Using External Crates

Add dependencies to your Cargo.toml:

🔸 Cargo.toml

[dependencies]
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }

🔸 main.rs

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_number: u32 = rng.gen_range(1..=100);
    
    println!("Random number: {}", random_number);
}

Output:

Random number: 42

🔹 Creating a Library Crate

Build reusable code with library crates:

🔸 src/lib.rs

/// A simple math library
pub mod math {
    /// Adds two numbers together
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    /// Multiplies two numbers
    pub fn multiply(a: i32, b: i32) -> i32 {
        a * b
    }
}

/// A greeting function
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

🔸 Using the library

use my_calculator::math;
use my_calculator::greet;

fn main() {
    let result = math::add(5, 3);
    let message = greet("Alice");
    
    println!("5 + 3 = {}", result);
    println!("{}", message);
}

🔹 Popular Crates

Essential crates for Rust development:

Common Crates:

  • serde - Serialization/deserialization
  • tokio - Async runtime
  • clap - Command line argument parsing
  • reqwest - HTTP client
  • rand - Random number generation
// Example using multiple crates
use clap::Parser;
use reqwest;
use serde::Deserialize;

#[derive(Parser)]
struct Args {
    #[arg(short, long)]
    url: String,
}

#[derive(Deserialize)]
struct Response {
    message: String,
}

#[tokio::main]
async fn main() -> Result<(), Box> {
    let args = Args::parse();
    let response: Response = reqwest::get(&args.url)
        .await?
        .json()
        .await?;
    
    println!("Response: {}", response.message);
    Ok(())
}

🧠 Test Your Knowledge

What file contains crate dependencies?