Skip to main content

IndexRustTutorial

Rust Modules, Crates and Cargo for Web Developers

Part 6 of Rust for web developers: modules and files, pub and privacy, library and binary crates, picking dependencies, features, clap and workspaces.

By LearnWebCraft Team22 min readBeginner

Part 6 of 15 · Rust for web developers

At the end of part 5, wordfreq was a single file of about 250 lines. It held argument parsing, word counting, sorting, statistics, error types, the output and all the tests. It works, but it's at the point where finding anything means scrolling, and adding a feature means touching code that has nothing to do with it.

Every language has an answer to this. In JavaScript it's files and import/export, plus npm for other people's code. Rust's answer covers the same ground with different words: modules organise code inside a crate, crates are the unit of compilation and sharing, Cargo manages the dependencies, and workspaces group several crates into one project.

In this part we'll split wordfreq into a library with modules and a thin binary on top, learn how Rust's privacy rules work, replace our hand-written argument parser with clap, look at how to choose crates and manage versions, and finish with a Cargo workspace, which is how we'll lay out the web app later in the series.

Everything below was run with Rust 1.100.0 and Cargo 1.100.0, with clap 4.6.10, anyhow 1.0.105 and colored 3.1.1.

The vocabulary

Rust's terms trip people up because two of them sound alike. Here's the mapping:

Rust What it is Closest JavaScript idea
Module A named scope for code inside a crate, often one file An ES module (a file with exports)
Crate A unit the compiler builds: one library or one binary A package's build output
Package A Cargo.toml and the crates it builds An npm package (package.json)
Workspace Several packages sharing one lock file and build folder A monorepo with npm, pnpm or Yarn workspaces
crates.io The public registry npmjs.com
Cargo.lock Exact resolved versions package-lock.json

A package can contain at most one library crate and any number of binary crates. By convention, src/lib.rs is the root of the library and src/main.rs is the root of the binary. Up to now wordfreq has only had a binary.

Modules

A module per file

In JavaScript, every file is a module automatically. In Rust, a file only becomes part of the program when its parent declares it. Here's a tiny project with src/main.rs and src/text.rs:

Fig. 1rust
// src/text.rs
pub fn slugify(title: &str) -> String {
    title.to_lowercase().replace(' ', "-")
}
Fig. 2rust
// src/main.rs
use crate::text::slugify;

fn main() {
    println!("{}", slugify("Hello World"));
}
Fig. 3text
error[E0432]: unresolved import `crate::text`
 --> src/main.rs:1:12
  |
1 | use crate::text::slugify;
  |            ^^^^ could not find `text` in the crate root

The file exists, but the compiler never looked at it. Nobody declared it. Add one line to main.rs:

Fig. 4rust
mod text;
Fig. 5text
hello-world

mod text; tells the compiler "there is a module called text, go and read it from text.rs (or text/mod.rs)". The module tree is built from the root file downwards, by these declarations, not by scanning the folder. This catches people out, and the fix is always the same: add the mod line in the parent.

Two other things to know:

  1. Modules can be nested. For mod handlers; in main.rs with mod users; inside handlers.rs, the files are src/handlers.rs and src/handlers/users.rs. The older style put the parent in src/handlers/mod.rs instead. Both work, and you'll see both in real code, but the newer handlers.rs style is what the Rust book now recommends.
  2. A module can also be written inline with braces, mod tests { ... }. That's what #[cfg(test)] mod tests has been all along: a module that's only compiled when testing.

Paths and use

Items inside modules are reached by paths, with :: as the separator:

  • crate::text::slugify starts from the root of the current crate, like an absolute path.
  • super::something means the parent module, like ../ in an import.
  • self::something means the current module.
  • std::collections::HashMap and clap::Parser start with a crate name.

use brings a path into scope so you can write the short name, exactly like a named import:

JavaScript Rust
import { slugify } from "./text.js" use crate::text::slugify;
import { a, b } from "./util.js" use crate::util::{a, b};
import * as util from "./util.js" use crate::util; then util::a()
import { x as y } from "./m.js" use crate::m::x as y;
export { a } from "./a.js" pub use crate::a::a;

The convention for functions is to import the parent module and call module::function(), so it's clear where the function lives. For types, import the type itself: use std::collections::HashMap;, not collections::HashMap at every use.

Privacy

Everything in Rust is private by default. A function, struct, field or module is only visible inside the module where it's defined, and that module's children, unless you mark it pub. This is the reverse of JavaScript, where everything at the top of a file is reachable once you export it, and class fields are public unless marked with #.

There are a few levels:

Visibility Who can use it
(nothing) This module and its children
pub(super) The parent module too
pub(crate) Anywhere in this crate, but not other crates
pub Everyone, including other crates that depend on this one

Struct fields are private separately from the struct. A pub struct Config { path: String } can be named from outside, but its path field can't be read or set, which also means outside code can't construct it with a literal. That's how Rust libraries keep invariants: make the fields private and provide a new function that checks them.

We'll see these errors on real code once wordfreq is split up.

Splitting wordfreq into a library and a binary

Here's the plan:

Fig. 6text
wordfreq/
├── Cargo.toml
├── src/
│   ├── lib.rs       the library root: declares modules, re-exports the API
│   ├── count.rs     counting, sorting, SortBy
│   ├── report.rs    line and word statistics
│   └── main.rs      the binary: arguments, reading the file, printing
└── tests/
    └── library.rs   integration tests against the public API

Why a library at all, for a command line tool? Because the binary does input and output, and everything else is logic that doesn't care where the text came from. Putting the logic in a library makes it testable without running the program, reusable from another binary, and, later, callable from a web handler. The Rust book's own command line example, minigrep, does exactly this split, and it's the standard shape for Rust tools.

lib.rs

Fig. 7rust
//! Count words in text and report the most common ones.

pub mod count;
pub mod report;

pub use count::{SortBy, count_words, top_words};
pub use report::Report;

pub mod count; declares the module and makes it public. The pub use lines re-export the most important items at the top of the crate, so users can write wordfreq::Report instead of wordfreq::report::Report. This is the same idea as an index.ts barrel file. The //! comment documents the crate itself.

count.rs

Fig. 8rust
use std::collections::HashMap;

/// How to order the words in a report.
#[derive(Debug, Clone, Copy, PartialEq, clap::ValueEnum)]
pub enum SortBy {
    /// Most frequent first
    Count,
    /// Alphabetical
    Alpha,
    /// Longest first
    Length,
}

/// Count each word in `text`, ignoring case and surrounding punctuation.
pub fn count_words(text: &str) -> HashMap<String, usize> {
    let mut counts = HashMap::new();

    for raw in text.split_whitespace() {
        let word = normalise(raw);
        if word.is_empty() {
            continue;
        }
        *counts.entry(word).or_insert(0) += 1;
    }

    counts
}

/// The first `n` words, ordered by `sort`.
pub fn top_words(counts: &HashMap<String, usize>, n: usize, sort: SortBy) -> Vec<(&str, usize)> {
    // ... unchanged from part 5, except the Length arm uses char_len ...
}

pub(crate) fn char_len(word: &str) -> usize {
    word.chars().count()
}

fn normalise(raw: &str) -> String {
    raw.trim_matches(|c: char| !c.is_alphanumeric())
        .to_lowercase()
}

Three visibility levels in one file:

  • count_words, top_words and SortBy are pub, the public API.
  • char_len is pub(crate), because report.rs needs it too, but it's not something users of the library should depend on.
  • normalise is private. It's an implementation detail of counting. I pulled it out of count_words so it has a name and its own test.

/// comments are doc comments. They show up in your editor's hover, in cargo doc, and, as you'll see shortly, in clap's help text.

The tests for these functions stay in the same file, in a #[cfg(test)] mod tests block at the bottom. Because tests is a child module, use super::*; brings in everything from count, including the private normalise, so unit tests can test private functions. That's a deliberate design choice in Rust, and it's handy.

report.rs

The statistics that used to be loose variables in main become a struct with a constructor:

Fig. 9rust
use crate::count::{char_len, count_words};
use std::collections::HashMap;

/// Summary statistics for a piece of text.
#[derive(Debug, PartialEq)]
pub struct Report {
    pub lines: usize,
    pub words: usize,
    pub unique: usize,
    pub longest: String,
    pub average: f64,
}

impl Report {
    /// Build a report, or `None` if the text has no words.
    pub fn from_text(text: &str) -> Option<Report> {
        let counts = count_words(text);
        if counts.is_empty() {
            return None;
        }
        let words = text.split_whitespace().count();
        let lines = text.lines().count();
        Some(Report {
            lines,
            words,
            unique: counts.len(),
            longest: longest_word(&counts).to_string(),
            average: words as f64 / lines as f64,
        })
    }
}

use crate::count::{char_len, count_words}; imports from a sibling module through the crate root. longest_word moved here too, as a private function, since only the report uses it.

Notice longest is now a String, not a &str. In part 3 terms: the counts map is created inside from_text and dropped when it returns, so a &str pointing into it would dangle. The report has to own its data. If you write longest: longest_word(&counts) without .to_string(), the compiler stops you, and you know why now.

from_text returns Option<Report> because empty text has no meaningful report. That pushes the empty-file decision to the caller, which is the right place for it.

What privacy looks like from outside

To see the rules in action, I made a second package that depends on wordfreq by path and tried to reach inside:

Fig. 10rust
fn main() {
    println!("{}", wordfreq::count::normalise("Hi!"));
}
Fig. 11text
error[E0603]: function `normalise` is private
  --> src/bin/e_private_fn.rs:2:37
   |
 2 |     println!("{}", wordfreq::count::normalise("Hi!"));
   |                                     ^^^^^^^^^ private function
   |
note: the function `normalise` is defined here
  --> /w/wordfreq/src/count.rs:50:1
   |
50 | fn normalise(raw: &str) -> String {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And the pub(crate) one, which is public inside wordfreq but not to anyone else:

Fig. 12text
error[E0603]: function `char_len` is private
  --> src/bin/e_crate_vis.rs:2:37
   |
 2 |     println!("{}", wordfreq::count::char_len("café"));
   |                                     ^^^^^^^^ private function
   |
note: the function `char_len` is defined here
  --> /w/wordfreq/src/count.rs:46:1
   |
46 | pub(crate) fn char_len(word: &str) -> usize {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

From outside the crate, pub(crate) is just private. This gives you a clean way to share helpers between your own modules without committing to them as public API.

Integration tests

Files in a tests/ folder next to src/ are integration tests. Each file is compiled as a separate crate that uses your library the way an outside user would, so it can only see pub items:

Fig. 13rust
// tests/library.rs
use wordfreq::{Report, SortBy, count_words, top_words};

#[test]
fn report_for_a_small_text() {
    let report = Report::from_text("one two two\nthree three three").unwrap();
    assert_eq!(report.lines, 2);
    assert_eq!(report.words, 6);
    assert_eq!(report.unique, 3);
    assert_eq!(report.longest, "three");
}

#[test]
fn public_api_sorts_alphabetically() {
    let counts = count_words("pear apple fig");
    let words: Vec<&str> = top_words(&counts, 3, SortBy::Alpha)
        .into_iter()
        .map(|(w, _)| w)
        .collect();
    assert_eq!(words, ["apple", "fig", "pear"]);
}

cargo test now runs several groups:

Fig. 14text
running 6 tests
test result: ok. 6 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
running 2 tests
test result: ok. 2 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

In order: the six unit tests inside the library modules, the binary's unit tests (none), the two integration tests, and doc tests (none yet). Part 14 goes much further with testing, including the same split for an Axum app: unit tests next to the code, integration tests that call the app from outside.

Using crates: clap

Our hand-written argument parser from parts 4 and 5 was a good exercise in pattern matching. For real tools, nearly everyone uses clap, and once you see it you'll understand why.

Fig. 15bash
cargo add clap --features derive
cargo add anyhow colored

The derive feature lets you describe your arguments as a struct:

Fig. 16rust
use clap::Parser;
use std::path::PathBuf;

/// Count the words in a text file and show the most common ones.
#[derive(Debug, Parser)]
#[command(version)]
struct Cli {
    /// The file to read
    path: PathBuf,

    /// How many words to show
    #[arg(short, long, default_value_t = 5,
          value_parser = clap::builder::RangedU64ValueParser::<usize>::new().range(1..))]
    top: usize,

    /// How to order the words
    #[arg(short, long, value_enum, default_value_t = SortBy::Count)]
    sort: SortBy,
}

A field without #[arg] is a positional argument. short, long gives you -t and --top. value_enum works because SortBy derives clap::ValueEnum, which you saw in count.rs. The doc comments become the help text, including the ones on each SortBy variant. PathBuf is the owned path type from the standard library, the path equivalent of String.

Our whole main is now:

Fig. 17rust
use anyhow::Context;
use clap::Parser;
use colored::Colorize;
use std::fs;
use std::path::PathBuf;
use wordfreq::{Report, SortBy, count_words, top_words};

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    let text = fs::read_to_string(&cli.path)
        .with_context(|| format!("could not read {}", cli.path.display()))?;

    let Some(report) = Report::from_text(&text) else {
        println!("{} has no words in it", cli.path.display());
        return Ok(());
    };

    println!(
        "{} lines, {} words, {} unique",
        report.lines, report.words, report.unique
    );
    println!(
        "longest word: {} ({} chars)",
        report.longest,
        report.longest.chars().count()
    );
    println!("{:.1} words per line", report.average);
    println!("sorted by {:?}", cli.sort);
    println!();

    let counts = count_words(&text);
    for (rank, (word, count)) in top_words(&counts, cli.top, cli.sort)
        .into_iter()
        .enumerate()
    {
        let bar = "#".repeat(count);
        println!("{:>2}. {:<10} {count:>3} {bar}", rank + 1, word.bold());
    }

    Ok(())
}

Note use wordfreq::... at the top. The binary uses the library through its public API, exactly like an outside crate would. And main returns anyhow::Result, which part 5 recommended for application code, so WordfreqError and the Config parser are both gone. That's about 80 lines of code we no longer maintain.

Here's what we got for free:

Fig. 18bash
cargo run -q -- --help
Fig. 19text
Count the words in a text file and show the most common ones

Usage: wordfreq [OPTIONS] <PATH>

Arguments:
  <PATH>
          The file to read

Options:
  -t, --top <TOP>
          How many words to show
          
          [default: 5]

  -s, --sort <SORT>
          How to order the words

          Possible values:
          - count:  Most frequent first
          - alpha:  Alphabetical
          - length: Longest first
          
          [default: count]

  -h, --help
          Print help (see a summary with '-h')

  -V, --version
          Print version

--version prints wordfreq 0.1.0, taken from Cargo.toml. Short flags work, in any order:

Fig. 20bash
cargo run -q -- notes.txt -t 3 -s length
Fig. 21text
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line
sorted by Length

 1. compiler     2 ##
 2. fetches      1 #
 3. helpful      1 #

And the errors are clear, with exit status 2, the usual convention for usage errors:

Fig. 22text
error: invalid value 'random' for '--sort <SORT>'
  [possible values: count, alpha, length]

For more information, try '--help'.
Fig. 23text
error: the following required arguments were not provided:
  <PATH>

Usage: wordfreq <PATH>

For more information, try '--help'.

The range check on --top works too, though the message shows its programmer roots:

Fig. 24text
error: invalid value '0' for '--top <TOP>': 0 is not in 1..18446744073709551615

That number is the largest u64. If it bothers you, clap also accepts a plain function fn(&str) -> Result<usize, String> as a value_parser, and you can write your own message. That's exercise 2.

A missing file goes through anyhow, with the context we added:

Fig. 25text
Error: could not read nope.txt

Caused by:
    No such file or directory (os error 2)

That "Caused by" chain is what anyhow prints when main returns its error. Exit status is 1.

Choosing dependencies

cargo add makes adding a crate trivially easy, so it's worth having a habit for deciding whether you should. Here's the checklist I use, and none of it is specific to Rust:

  1. Check its page on crates.io: recent downloads, the date of the last release, and the number of reverse dependencies. A crate used by thousands of others has had a lot of eyes on it.
  2. Check its documentation on docs.rs, which builds docs for every published crate automatically. If the docs are thin, using it will be harder.
  3. Check the repository: open issues, whether pull requests get answered, and whether there's more than one maintainer.
  4. Check what it pulls in. Run cargo tree after adding it.

For finding crates in the first place, blessed.rs is a community-maintained list of the usual choice for common jobs, and lib.rs is an alternative crates.io front end with better search and categories. For web work in this series, the crates we'll use are the ones that appear at the top of both: tokio, axum, serde, sqlx, tracing and a few more.

Looking at the tree

Fig. 26bash
cargo tree --depth 1
Fig. 27text
wordfreq v0.1.0 (/w)
├── anyhow v1.0.105
├── clap v4.6.10
└── colored v3.1.1

Without --depth 1 you see the full tree, including what clap depends on. For this project there are 20 unique packages on Linux, including wordfreq itself. The exact list varies a little by platform, because some crates only pull in Windows-specific dependencies on Windows. That's modest. A web server with a database driver will be well over a hundred, which is normal for Rust and similar to a small Express app's node_modules, though Rust crates are compiled into your binary instead of shipped alongside it.

cargo tree -i some_crate (for "invert") answers the question "why is this in my build?" by showing which of your dependencies pulled it in. It's the Rust version of npm why.

Versions and Cargo.lock

Here's what cargo add wrote into Cargo.toml:

Fig. 28toml
[dependencies]
anyhow = "1.0.105"
clap = { version = "4.6.10", features = ["derive"] }
colored = "3.1.1"

"1.0.105" looks like an exact version, but it isn't. Cargo treats a bare version as a caret requirement, the same as ^1.0.105 in npm: any version from 1.0.105 up to, but not including, 2.0.0. Rust crates follow semantic versioning closely, and Cargo assumes that anything below the next major version is compatible. For crates still below 1.0, the rule shifts one place: "0.8.4" allows 0.8.x but not 0.9.

Cargo.lock records the exact version of every crate in the tree, like package-lock.json. The current advice from the Cargo team is to commit Cargo.lock for every project, libraries included. cargo update moves locked versions forward within your requirements, and cargo update -p clap does it for one crate.

Features

features = ["derive"] turns on an optional part of clap. Features are Cargo's way of letting crates offer optional functionality without forcing everyone to compile it. clap's derive macros are optional because people who build arguments by hand don't need them.

You'll see features everywhere in web crates. tokio puts nearly everything behind features ("full" turns them all on). serde's "derive" feature gives you #[derive(Serialize, Deserialize)]. sqlx has features for each database and for each runtime. When an import doesn't resolve even though the crate is in your Cargo.toml, a missing feature is the first thing to check. The crate's docs.rs page lists its features, and items that need a feature are labelled with it.

Dev dependencies

Crates you only need for tests go under [dev-dependencies], with cargo add --dev some_crate. They're not compiled into your release binary. In part 14 we'll use a few for testing the Axum app.

Workspaces

Bigger Rust projects are usually several crates in one repository: maybe a library of domain logic, a web server, a command line admin tool and a background worker. A workspace ties them together. I built a small one to show the shape:

Fig. 29text
ws/
├── Cargo.toml          the workspace root
├── Cargo.lock          one lock file for everything
├── crates/
│   ├── api/            a binary crate
│   └── textstats/      a library crate
└── target/             one build folder for everything

The root Cargo.toml has no [package], only a [workspace]:

Fig. 30toml
[workspace]
members = ["crates/*"]
resolver = "3"

[workspace.dependencies]
anyhow = "1.0"

members lists the packages, and a glob works. resolver = "3" selects the newest dependency resolver, the default for edition 2024 packages. [workspace.dependencies] declares versions once at the top, so every member uses the same one.

Inside crates/api/Cargo.toml, one member depends on another by path, and inherits a shared dependency:

Fig. 31toml
[dependencies]
textstats = { version = "0.1.0", path = "../textstats" }
anyhow.workspace = true

Running a specific member uses -p:

Fig. 32bash
cargo run -q -p api
Fig. 33text
5 words

One thing I didn't expect: when I built this, Cargo 1.100 warned me about anyhow, which I'd added but not used yet:

Fig. 34text
warning: unused dependency `anyhow`
 --> crates/api/Cargo.toml:8:1
  |
8 | anyhow.workspace = true
  | ^^^^^^
  |
  = note: `cargo::unused_dependencies` is set to `warn` by default
help: consider removing the dependency on `anyhow`

That's a recent addition to Cargo and a welcome one. In the npm world you'd need a separate tool like depcheck to find unused packages.

The benefits of a workspace are mostly about consistency and build time. All members share one Cargo.lock, so there's exactly one version of each dependency. They share one target/ folder, so a crate used by three members is compiled once. And cargo test at the root tests everything.

For the Axum app in this series, we'll start with a single package to keep the moving parts down, and I'll point out the moment where splitting into a workspace starts to pay off.

Useful Cargo commands

Here's a reference of the Cargo commands you've now met, plus a few more worth knowing:

Command What it does npm equivalent
cargo add serde --features derive Add a dependency npm install serde
cargo add --dev pretty_assertions Add a test-only dependency npm install -D ...
cargo remove anyhow Remove a dependency npm uninstall
cargo tree Show the dependency tree npm ls --all
cargo tree -i syn Why is this crate here? npm why syn
cargo update Update within version ranges npm update
cargo doc --open Build and open docs for your crate and every dependency (no direct equivalent)
cargo install ripgrep Install a binary from crates.io npm install -g
cargo run -p api Run one workspace member npm run -w api
cargo test -p textstats Test one workspace member npm test -w textstats

cargo doc --open deserves a special mention. It builds HTML documentation for your crate and every dependency, at the exact versions you're using, and opens it locally. When you're offline, or using an older version of a crate, it's often better than searching the web.

Two community tools worth installing once you have a real project: cargo-audit checks your Cargo.lock against the RustSec advisory database for known vulnerabilities, like npm audit, and cargo-deny can also enforce license rules and ban specific crates. Both install with cargo install.

Exercises

  1. Move SortBy into its own module, src/sort.rs, and update the imports. Do users of the library need to change their code? Why not?
  2. Replace the RangedU64ValueParser on --top with your own function fn parse_top(s: &str) -> Result<usize, String> that gives a friendlier message, and pass it as value_parser = parse_top.
  3. Add a --min option with clap that hides words with fewer than N occurrences. Put the filtering logic in the library, not in main, and give it an integration test.
  4. Run cargo doc --open on wordfreq. Find your doc comments. Then add an example to the doc comment on count_words inside a code block, and run cargo test again. What changed in the doc test count?
  5. Make the wordfreq folder into a workspace with two members: wordfreq-core, the library, and wordfreq, the binary. What has to change in main.rs?

Next up: traits, generics and closures

We've used traits all through this part without defining one: Debug, Clone, PartialEq, Display, clap's Parser and ValueEnum. We've also used generics (Vec<T>, Option<T>, HashMap<K, V>) and closures (|a, b| b.1.cmp(&a.1)) without looking at how they work. Part 7 covers all three. Traits are Rust's version of interfaces, generics let you write one function for many types, and closures are Rust's anonymous functions, with the ownership rules that make them a little different from JavaScript's arrow functions. They're also the three features Axum is built on, so this is where the series starts turning toward the web.