Skip to content

Chapter 6 of 8

Modules, Crates, Cargo, and Testing

Rust organizes code using modules, declared with the `mod` keyword. A module is a namespace that can hold functions, structs, enums, constants, and other modules. Items inside a module are private by default and become visible to outside code only when marked `pub`. This explicit visibility model lets library authors expose a precise public API while keeping implementation details hidden from consumers.

Modules can be defined inline or placed in separate files. The declaration `mod foo;` instructs the compiler to look for either `foo.rs` alongside the parent or a `foo/mod.rs` directory. Since Rust 2018, the convention of using `foo.rs` with a sibling `foo/` directory for submodules has become preferred because it avoids the clutter of `mod.rs` and reads more naturally.

Cargo is Rust's build system and package manager. Common commands include `cargo new` to scaffold a project, `cargo build` to compile, `cargo run` to build and execute, and `cargo test` to run the test suite. Dependencies are declared in `Cargo.toml`, and external libraries are downloaded from crates.io, the central registry of the Rust ecosystem.

A crate is the unit of compilation in Rust. It is either a binary crate, which contains a `main` function and produces an executable, or a library crate, which exposes functionality for other crates to use. Tests are typically written in a `#[cfg(test)]` module within the same file as the code they exercise, using `#[test]` attributes on individual functions and macros such as `assert_eq!` and `assert!` to express expectations. Running `cargo test` compiles and executes them all.

All chapters
  1. 1Foundations of Rust Memory Safety
  2. 2Structures, Enums, and Pattern Matching
  3. 3Error Handling with Option and Result
  4. 4Traits, Generics, and Polymorphism
  5. 5Iterators, Closures, and Functional Patterns
  6. 6Modules, Crates, Cargo, and Testing
  7. 7Concurrency in Rust
  8. 8Smart Pointers and Unsafe Rust

Drill it

Reading is not remembering. These come from the Rust Programming deck:

Q

What is Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It achieves memory safety without a garbage collector through its ownership sy...

Q

What is ownership in Rust?

Ownership is Rust's core memory management concept. Each value has exactly one owner, and when the owner goes out of scope, the value is dropped (freed). This p...

Q

What are the three ownership rules in Rust?

Each value in Rust has a single ownerThere can only be one owner at a timeWhen the owner goes out of scope, the value is dropped

Q

What is borrowing in Rust?

Borrowing lets you reference a value without taking ownership. You create a reference with &. The original owner retains ownership while the borrower can re...