RsRust
IntermediateLesson 13 of 16

Cargo, Modules & Tests – Rust

Structuring projects, managing dependencies, and testing code.

Every Cargo project (package) has a Cargo.toml. It holds metadata and dependencies (crates from crates.io). Cargo downloads them automatically and records the exact versions in Cargo.lock.

[package]
name = "hallo"
version = "0.1.0"
edition = "2021"

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

[profile.release]
opt-level = 3
cargo add rand        # add a dependency (writes it into Cargo.toml)
cargo build           # build
cargo test            # run tests
cargo fmt             # format code (rustfmt)
cargo clippy          # linter with improvement suggestions
cargo doc --open      # generate and open documentation

You organize code with modules. Everything is private by default, pub makes items public, and use brings names into scope. Modules can also be moved into their own files (mod utils; loads src/utils.rs).

mod geometrie {
    pub struct Punkt {
        pub x: f64,
        pub y: f64,
    }

    pub fn abstand(a: &Punkt, b: &Punkt) -> f64 {
        ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt()
    }

    fn geheim() {}   // private: only visible inside geometrie
}

use geometrie::{abstand, Punkt};

fn main() {
    let a = Punkt { x: 0.0, y: 0.0 };
    let b = Punkt { x: 3.0, y: 4.0 };
    println!("{}", abstand(&a, &b));   // 5
}

Tests are built into the language: functions marked #[test], usually in a tests module that is only compiled when testing. cargo test runs them in parallel and also runs code examples from doc comments.

pub fn addiere(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn addiert_richtig() {
        assert_eq!(addiere(2, 3), 5);
    }

    #[test]
    #[should_panic]
    fn panik_erwartet() {
        panic!("boom");
    }
}
TipFor larger projects there are workspaces: several crates in one repository with a shared Cargo.lock and a shared target folder. Integration tests live in the tests/ folder next to src/.
WarningDo not depend on * versions: rand = "*" makes builds non-reproducible. Use the compatible default notation ("0.8").