---
title: "Crates, modules and cargo test"
slug: "crates-modules-and-tests"
description: "Split code into modules, make items pub, write unit tests and run cargo test. Fix a private function, then build a small tested command-line tool."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/crates-modules-and-tests"
---

# Crates, modules and cargo test

How do you organise a Rust project and prove it works?

## Predict

```rust
mod count {
    pub fn words(s: &str) -> usize {
        s.split_whitespace().count()
    }
}

fn main() {
    println!("{}", count::words("one two three"));
    println!("{}", count::words("  spaced   out  "));
    println!("{}", count::words("one,two"));
}
```

What does this program print?

- 3, 2, 2
- 3, 4, 1
- 3, 2, 1

Answer: 3, 2, 1 — The spaces separate words, and one,two has none, so it counts as one.

Output:

```
3
2
1
```

`split_whitespace` splits only on whitespace and ignores extra spaces. `one,two` has none, so it is one word.

## Packages, crates and modules

A **package** has a `Cargo.toml`. It holds **crates**: a binary crate starts at `src/main.rs`, a library crate at `src/lib.rs`. Inside a crate, `mod` declares a module, and its items are private until you mark them `pub`. `use` brings a path into scope, so `count::words` becomes `words`. `cargo add <name>` adds a dependency from crates.io.

## A module and use

```rust
mod count {
    pub fn words(s: &str) -> usize {
        s.split_whitespace().count()
    }

    pub fn lines(s: &str) -> usize {
        s.lines().count()
    }
}

use count::{lines, words};

const TEXT: &str = "first line\nsecond line here\nthird\n";

fn main() {
    println!("lines {}", lines(TEXT));
    println!("words {}", words(TEXT));
    println!("bytes {}", TEXT.len());
}
```

Output:

```
lines 3
words 6
bytes 34
```

The module is written inline so the example fits one file. In a project it would sit in `src/lib.rs` or in its own file. `use count::{lines, words};` lets `main` call both by their short names.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=b7c93d86775f1c74a0e502052d0a08f0

## Tests with cargo test

Unit tests sit next to the code, in a module marked `#[cfg(test)]`. A function marked `#[test]` is one test, and it fails if it panics, for example when `assert_eq!` finds two different values. `cargo test` builds and runs them all. Integration tests live in a `tests/` folder and use your crate like an outside user would.

## Unit tests in src/lib.rs

```rust
pub fn words(s: &str) -> usize {
    s.split_whitespace().count()
}

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

    #[test]
    fn counts_words() {
        assert_eq!(words("one two three"), 3);
    }

    #[test]
    fn ignores_extra_spaces() {
        assert_eq!(words("  spaced   out  "), 2);
    }

    #[test]
    fn empty_text_has_no_words() {
        assert_eq!(words(""), 0);
    }
}
```

Output:

```

running 3 tests
test tests::counts_words ... ok
test tests::empty_text_has_no_words ... ok
test tests::ignores_extra_spaces ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

```

The run times differ on every run, and so can the order of the three `test` lines, because tests run in parallel. The second block is for doc tests: this crate has none, so it runs 0 tests. In your own project, `cargo test` prints the same two blocks.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=369161d2d9f158791e096460d3c8a191

## Fix it

```rust
mod count {
    fn words(s: &str) -> usize {
        s.split_whitespace().count()
    }
}

fn main() {
    println!("{}", count::words("one two three"));
}
```

This program does not compile. What is the bug?

- The function words is private to module count, so main cannot call it
- main must be declared pub
- count::words is the wrong path

Answer: The function words is private to module count, so main cannot call it — Add pub in front of fn words.

Compiler message:

```
error[E0603]: function `words` is private
```

Fixed:

```rust
mod count {
    pub fn words(s: &str) -> usize {
        s.split_whitespace().count()
    }
}

fn main() {
    println!("{}", count::words("one two three"));
}
```

Output:

```
3
```

## Say it back

In your own words: what does pub change?

Our sentence: Items in a module are private by default. pub makes an item visible outside the module, so code elsewhere can call it.

## Mission (20 min)

Build wc-lite, a tiny word counter. Put pub fn words and pub fn lines and a tests module in src/lib.rs. In src/main.rs read the file named by the first argument and print its lines, words and bytes, or a clear message when the argument is missing.

```sh
cargo new wc-lite && cd wc-lite
cargo test
cargo run -- Cargo.toml
```

## Common questions

### What is the difference between a crate and a package?

A crate is one unit of compilation: a binary with a main function, or a library. A package is what cargo manages: it has a Cargo.toml and holds one or more crates. cargo new creates a package with a binary crate, and cargo new --lib creates one with a library crate.

### How do I add a dependency to a Rust project?

Run cargo add followed by the crate name inside your project. Cargo finds it on crates.io and writes it into Cargo.toml under dependencies. The next cargo build downloads and compiles it. Then use its items with a use line, for example use rand::Rng. You can also edit Cargo.toml by hand.

### Where do I put tests in Rust?

Unit tests go in the same file as the code, inside a module marked #[cfg(test)], with each test marked #[test]. Integration tests go in a tests folder next to src and can only use your public API. Run both kinds with cargo test. A test that panics fails, and assert_eq! panics when the values differ.

## Sources

- https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch11-01-writing-tests.html (read 2026-12-03)
- https://doc.rust-lang.org/cargo/commands/cargo-test.html (read 2026-12-03)

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03.
