Skip to content
RustLearn

Module 10 Exercises — Modules, Crates & Project Layout

How to use this page

Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.

Before you start, be able to state:

  • the difference between what mod does and what use does;
  • why everything is private by default and what pub use is for;
  • where Cargo looks for the file behind mod network;.

Do the multi-file drills in a real project rather than reading them. Module layout is muscle memory, and the compiler's messages here are unusually good teachers — each one names the exact file or path it expected.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 10.1 — Nested modules

Create a single-file crate with mod math { pub mod basic { pub fn add(..) } mod secret { .. } } and call add from main using both an absolute and a relative path. Then try calling something from secret and record the error.

Solution
rust
mod math {
    pub mod basic {
        pub fn add(a: i32, b: i32) -> i32 { a + b }
    }
    mod secret {
        pub fn hidden() -> i32 { 42 }
    }
    pub fn use_secret() -> i32 { secret::hidden() }   // parent CAN'T, sibling CAN
}

fn main() {
    println!("{}", crate::math::basic::add(1, 2));
    println!("{}", math::basic::add(3, 4));
    println!("{}", math::use_secret());
    // println!("{}", math::secret::hidden());  // E0603: module `secret` is private
}

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 10.2 — Split a project into files

Take a single-file program with a Shape enum, an area function, and formatting helpers, and split it into src/lib.rs, src/shapes.rs, src/format.rs, plus a thin src/main.rs. Re-export Shape from lib.rs so users write mycrate::Shape.

Solution
rust
// src/lib.rs
mod shapes;
mod format;

pub use shapes::Shape;
pub use format::describe;

// src/shapes.rs
#[derive(Debug, Clone, Copy)]
pub enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
}

impl Shape {
    pub fn area(&self) -> f64 {
        match self {
            Shape::Circle(r) => std::f64::consts::PI * r * r,
            Shape::Rect { w, h } => w * h,
        }
    }
}

// src/format.rs
use crate::shapes::Shape;

pub fn describe(s: &Shape) -> String {
    format!("{s:?} has area {:.2}", s.area())
}

// src/main.rs
use mycrate::{describe, Shape};

fn main() {
    println!("{}", describe(&Shape::Circle(2.0)));
    println!("{}", describe(&Shape::Rect { w: 3.0, h: 4.0 }));
}

🟡 Exercise 10.3 — Visibility puzzle

Make this compile by changing only visibility modifiers — no restructuring:

rust
mod outer {
    struct Config { name: String, retries: u32 }

    impl Config {
        fn new(name: &str) -> Config {
            Config { name: name.to_string(), retries: 3 }
        }
    }

    mod inner {
        fn helper() -> u32 { 7 }
    }

    fn use_inner() -> u32 { inner::helper() }
}

fn main() {
    let c = outer::Config::new("app");
    println!("{} {}", c.name, c.retries);
    println!("{}", outer::use_inner());
}
Solution
rust
mod outer {
    pub struct Config { pub name: String, pub retries: u32 }

    impl Config {
        pub fn new(name: &str) -> Config {
            Config { name: name.to_string(), retries: 3 }
        }
    }

    mod inner {
        pub(super) fn helper() -> u32 { 7 }   // visible to `outer` only
    }

    pub fn use_inner() -> u32 { inner::helper() }
}

Note pub(super) keeps helper invisible outside outer — exactly the granularity you want in real code.

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 10.4 — Workspace

Create a workspace with three crates:

  • calc-core (library): pub fn evaluate(expr: &str) -> Result<f64, CalcError>
  • calc-cli (binary): reads an expression from argv and prints the result
  • shared dependency versions declared in [workspace.dependencies]

Then add an integration test in calc-core/tests/ and verify cargo test at the root runs it.

Solution sketch
calc/
├── Cargo.toml
├── calc-core/
│   ├── Cargo.toml
│   ├── src/lib.rs
│   └── tests/eval.rs
└── calc-cli/
    ├── Cargo.toml
    └── src/main.rs
toml
# calc/Cargo.toml
[workspace]
members = ["calc-core", "calc-cli"]
resolver = "2"

[workspace.dependencies]
thiserror = "1"
toml
# calc-cli/Cargo.toml
[dependencies]
calc-core = { path = "../calc-core" }
rust
// calc-core/src/lib.rs
use thiserror::Error;

#[derive(Debug, Error, PartialEq)]
pub enum CalcError {
    #[error("empty expression")]
    Empty,
    #[error("bad token: {0}")]
    BadToken(String),
}

/// Evaluates a simple space-separated left-to-right expression: "2 + 3 * 4" == 20.
pub fn evaluate(expr: &str) -> Result<f64, CalcError> {
    let mut it = expr.split_whitespace();
    let first = it.next().ok_or(CalcError::Empty)?;
    let mut acc: f64 = first.parse().map_err(|_| CalcError::BadToken(first.into()))?;
    while let Some(op) = it.next() {
        let rhs = it.next().ok_or(CalcError::BadToken(op.into()))?;
        let rhs: f64 = rhs.parse().map_err(|_| CalcError::BadToken(rhs.into()))?;
        acc = match op {
            "+" => acc + rhs,
            "-" => acc - rhs,
            "*" => acc * rhs,
            "/" => acc / rhs,
            other => return Err(CalcError::BadToken(other.into())),
        };
    }
    Ok(acc)
}
rust
// calc-core/tests/eval.rs
use calc_core::{evaluate, CalcError};

#[test]
fn left_to_right() {
    assert_eq!(evaluate("2 + 3 * 4").unwrap(), 20.0);
}

#[test]
fn empty_is_error() {
    assert_eq!(evaluate("").unwrap_err(), CalcError::Empty);
}
rust
// calc-cli/src/main.rs
fn main() {
    let expr: Vec<String> = std::env::args().skip(1).collect();
    match calc_core::evaluate(&expr.join(" ")) {
        Ok(v) => println!("{v}"),
        Err(e) => { eprintln!("error: {e}"); std::process::exit(1); }
    }
}

Self-check

  1. What's the difference between a package and a crate?
  2. Why doesn't creating src/helpers.rs make its contents available?
  3. What does pub use buy you that pub mod doesn't?
  4. Which visibility modifier is right for "internal to my crate, not part of the API"?
  5. Why do most binaries also have a lib.rs?
Answers
  1. A package is one Cargo.toml and may hold several crates; a crate is one compilation unit with a single root file.
  2. Files are not modules automatically — you must write mod helpers; in the parent.
  3. It decouples the public API from the internal file layout, letting you present a flat surface over a deep tree.
  4. pub(crate).
  5. Integration tests, benches, examples, and other crates can only depend on a library, so keeping logic in lib.rs makes it testable and reusable.

Next: Module 11 — Generics