FerrousPath

Level 1 · Foundations· Lesson 10 of 10 · 25 min

Modules, crates and Cargo

Organising code into modules, controlling visibility, using dependencies from crates.io — and a first project.

Packages, crates, modules

  • A crate is a unit of compilation: either a binary (has main) or a library.
  • A package is what cargo new creates: a Cargo.toml plus one or more crates.
  • A module is a namespace inside a crate.

src/main.rs is the root of a binary crate; src/lib.rs is the root of a library crate. A package can have both.

Modules and visibility

mod kitchen {
    pub struct Order {
        pub dish: String,
        notes: String, // private field
    }

    impl Order {
        pub fn new(dish: &str) -> Order {
            Order { dish: dish.to_string(), notes: String::new() }
        }

        pub fn summary(&self) -> String {
            format!("{} ({})", self.dish, quality_check(&self.notes))
        }
    }

    fn quality_check(notes: &str) -> &'static str {
        if notes.is_empty() { "standard" } else { "custom" }
    }

    pub mod pantry {
        pub fn stock() -> u32 {
            super::secret_reserve() + 10 // `super` is the parent module
        }
    }

    fn secret_reserve() -> u32 {
        5
    }
}

use kitchen::Order;

fn main() {
    let order = Order::new("ramen");
    println!("{}", order.summary());
    println!("{}", kitchen::pantry::stock());
    // order.notes;               // ❌ private field
    // kitchen::quality_check(""); // ❌ private function
}

Everything is private by default. pub makes an item visible to the parent module. A struct’s fields have their own visibility, so a type can be public while its representation stays hidden — this is how you protect invariants. pub(crate) means “visible anywhere in this crate, but not outside it”.

Paths: crate:: starts at the crate root, super:: at the parent, self:: at the current module. use brings a path into scope.

Modules in files

Real projects put modules in separate files:

src/
├── main.rs          // contains: mod kitchen;
├── kitchen.rs       // the contents of the kitchen module; contains: pub mod pantry;
└── kitchen/
    └── pantry.rs    // the contents of kitchen::pantry

mod kitchen; (with a semicolon) tells the compiler to load the module from kitchen.rs. You declare each module once, in its parent; everywhere else you use it. Files are not modules until some mod declaration says so.

Dependencies

Libraries live on crates.io. Add one with:

cargo add rand

which edits Cargo.toml:

[package]
name = "guess"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.9"

"0.9" means “any 0.9.x”: Cargo follows semantic versioning and will not pick a release that declares itself incompatible. The exact versions chosen are recorded in Cargo.lock. Documentation for every published crate is at docs.rs/<crate-name>.

Editions (2015, 2018, 2021, 2024) are opt-in language revisions. Crates on different editions interoperate freely, so the ecosystem never splits.

Project: a guessing game

Time to build something locally. Create a project, add rand, and write this in src/main.rs:

// crate: rand
use std::cmp::Ordering;
use std::io::{self, Write};

fn main() {
    let secret: u32 = rand::random_range(1..=100);
    let mut attempts = 0;

    loop {
        print!("Guess (1-100): ");
        io::stdout().flush().unwrap();

        let mut line = String::new();
        if io::stdin().read_line(&mut line).unwrap() == 0 {
            println!("\nNo more input. The number was {secret}.");
            break;
        }
        let Ok(guess) = line.trim().parse::<u32>() else {
            println!("Please type a number.");
            continue;
        };
        attempts += 1;

        match guess.cmp(&secret) {
            Ordering::Less => println!("Too small."),
            Ordering::Greater => println!("Too big."),
            Ordering::Equal => {
                println!("Correct in {attempts} attempts!");
                break;
            }
        }
    }
}

It uses nearly everything from this level: a dependency, mutable state, a loop, let else, match, and standard input. (The Run button works, but the Playground has no keyboard input — the program sees end-of-input immediately. Run it with cargo run to play.)

Level 1 checkpoint

Before moving on, you should be able to do these without looking anything up:

  • Explain why let b = a; invalidates a for a String but not for an i32.
  • State the borrowing rule and give an example the compiler rejects.
  • Model a small domain with a struct and an enum and write a match over it.
  • Write a function that returns Result and use ? inside it.

Exercises

  1. Extend the game: limit the player to 7 guesses and print the secret on failure.
  2. Move the comparison logic into a module game with a public function fn check(guess: u32, secret: u32) -> Verdict returning your own enum.
  3. Project. Write a command-line to-do list that keeps tasks in a Vec<Task> and understands add <text>, done <n>, list, and quit typed on standard input.

Check your understanding

Pick an answer to see the explanation.

  1. 1.What is the default visibility of a function inside a module?

  2. 2.Where does Cargo look for the code of mod network; declared in src/main.rs?

  3. 3.What is the purpose of Cargo.lock?

Key terms in this lesson

Finished the lesson and the exercises?