MARY.WIN

RUSTY — BEGINNER — B08

Modules and crates: namespaces, files and
visibility

Rust has no autoloader: you declare every module, everything starts private, and a crate from crates.io arrives through one line in `Cargo.toml`.
Lesson 8 of 9 in Rust beginner track. Before you start: Lesson 5.

You add a file called billing.rs next to main.rs, write a function in it, and call that function from main(). The compiler stops with E0433: it cannot find module or crate billing in this scope. The file is right there in the folder.

In PHP, Composer's PSR-4 autoloader would have found it. Rust has no autoloader. A file isn't part of the program until a line of code says so, and everything in it starts private.

Here is a version that works. The line after the comment, mod billing;, is what the failing version was missing.

This lesson covers how a Rust program is organized: the package, the crate and the module; how a module finds its file; where pub lets a call through; how use shortens a path; and how to add a crate from crates.io with cargo add and use it. It assumes Lesson 5, because Invoice is a struct with an impl block, and it comes back to the use std::collections::HashMap; line from Lesson 4. It shows one file layout and leaves out the others.¹ Project layouts with library and binary targets are in the main series. From PHP you already know namespaces, use and composer require. Rust has a place for each; what differs is that nothing finds your files for you, and everything starts private.

Take a look at Example 1.

Example 1. Complete example (modules-demo/src/main.rs)

// Lesson b08: files are modules, and `mod` is what registers them.
mod billing;

use billing::invoice::Invoice;

fn main() {
    let invoice = Invoice::new("INV-1", 2500);
    println!("{}", invoice.label());
    println!("tax = {}", billing::tax_cents(invoice.total_cents()));
    println!("full path works too: {}", crate::billing::invoice::Invoice::new("INV-2", 100).label());
}

It is the crate root of a small package in modules-demo/. From that folder, run it:

TERMINAL
cargo run --quiet
INV-1 ($25.00)
tax = 500
full path works too: INV-2 ($1.00)

The PHP version, php/b08_namespaces.php, prints the same three lines.

What are the three containers?

modules-demo/Cargo.toml is the Rust side of a composer.json, and inside it are three boxes that nest. The outer box is a package: one or more crates described by a single Cargo.toml. The middle box is a crate: the smallest amount of code the compiler considers at a time. A binary crate compiles to an executable from src/main.rs; a library crate is shared code, rooted at src/lib.rs. That first file is the crate root. The inner box is a module: a group of functions, types and other modules, private by default, in a tree below the crate root. It is the nearest thing Rust has to a PHP namespace.

Can one package hold two library crates? No. At most one library crate, and any number of binaries.

How does a module find its file?

In PHP, Composer's autoloader finds a class's file for you. In Rust, you write that step yourself. Take a look at Example 2, the failing version from the opening.

Example 2. The call without the declaration (modules-demo/missing-mod/src/main.rs)

fn main() {
    println!("{}", billing::tax_cents(2500));
}

From modules-demo/missing-mod, cargo build --quiet stops with this:

OUTPUT
error[E0433]: cannot find module or crate `billing` in this scope
 --> src/main.rs:2:20
  |
2 |     println!("{}", billing::tax_cents(2500));
  |                    ^^^^^^^ use of unresolved module or unlinked crate `billing`
  |
help: to make use of source file src/billing.rs, use `mod billing` in this file to declare the module
  |
1 + mod billing;
  |

For more information about this error, try `rustc --explain E0433`.
error: could not compile `billing-missing-mod` (bin "billing-missing-mod") due to 1 previous error

The help: line names the fix: use mod billing to declare the module. That is a mod declaration. mod billing; tells the compiler that a module named billing exists, and loads it from billing.rs. A file that no mod line names is not in the crate. The Rust Book is direct about it: mod is not an include. It adds a module to the tree.

In Example 1, mod billing; loads src/billing.rs. That file declares its own child, as Example 3 shows.

Example 3. The billing module (modules-demo/src/billing.rs)

// src/billing.rs is the module `billing`. Its child module lives in src/billing/invoice.rs.
pub mod invoice;

pub fn tax_cents(total_cents: u32) -> u32 {
    total_cents * 20 / 100
}

// Private by default: only code inside `billing` can call this.
#[allow(dead_code)]
fn internal_rounding_rule() -> u32 {
    1
}

pub mod invoice; on line 2 loads src/billing/invoice.rs. So a file in src/ belongs to the program when a mod line names it, written in the module that is its parent (the crate root for billing.rs, and billing.rs itself for billing/invoice.rs), and when that parent was declared the same way, all the way up to main.rs, and until a chain of those lines reaches it, it is a file in a folder.

Delete pub mod invoice; but keep the file. Is invoice still a module? No. Without the mod line, the compiler never reads the file.

Where does privacy stop a call?

The function internal_rounding_rule was private, and a comment above it said so: only code inside billing can call this. It took no arguments and returned 1. In a second copy of the package, main() called it anyway, by its full path, billing::internal_rounding_rule(). The compiler answered with E0603 and the word private, and pointed at line 10 of billing.rs, where the function had been all along.

Here is that second copy's main.rs and the message.

Example 4. Calling a private function (modules-demo/compile-fail/src/main.rs)

mod billing;

fn main() {
    println!("{}", billing::internal_rounding_rule());
}
OUTPUT
error[E0603]: function `internal_rounding_rule` is private
  --> src/main.rs:4:29
   |
 4 |     println!("{}", billing::internal_rounding_rule());
   |                             ^^^^^^^^^^^^^^^^^^^^^^ private function
   |
note: the function `internal_rounding_rule` is defined here
  --> src/billing.rs:10:1
   |
10 | fn internal_rounding_rule() -> u32 {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0603`.
error: could not compile `billing-private-call` (bin "billing-private-call") due to 1 previous error

Items are private to their module by default, and pub makes them visible outside it. The rule is called visibility: code can use an item in its own module or a descendant, or any pub item. It is PHP's public and private, decided per module instead of per class. So main() can call tax_cents(), which is pub, and not internal_rounding_rule(), which isn't. Invoice, in src/billing/invoice.rs, is a pub struct whose fields, number and total_cents, stay private; you read them through total_cents() and label().

Can code in invoice, a child of billing, call that private function? Yes. Children see their ancestors' items. Parents can't see into children.

Shorter names

crate::billing::invoice::Invoice, in the last println! of Example 1, is a path: an item's place in the module tree, with :: between the parts. A path that starts with crate:: begins at the crate root. For a short name, PHP writes use App\Billing\Invoice; and Rust also writes use. use billing::invoice::Invoice; changes how you refer to an item, not where it lives.

In Lesson 4 you wrote use std::collections::HashMap;. std is the standard library crate, and you can use it without listing it in Cargo.toml. Vec, String, Option and Result need no use at all: they are in the prelude, what Rust automatically imports into every program.

Does use billing::internal_rounding_rule; make it callable from main()? No. A use path is checked for privacy like any other. It's a shorter name, not permission.

Adding a crate from crates.io

In Laravel, when you want a package, composer require adds it to composer.json. Rust has a public registry, crates.io, and a package published there is called a crate, which gives the word a second use next to the compiler's. std needed no line in Cargo.toml. A crate from crates.io gets one, and the command that writes it is cargo add.

In a scratch package called slugs, run cargo add heck.² The recorded run printed this:

OUTPUT
    Updating crates.io index
      Adding heck v0.5.0 to dependencies
    Updating crates.io index
     Locking 1 package to highest Rust 1.100.0 compatible version

Example 5. The manifest after cargo add (b01-crate-demo/Cargo.toml)

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

[dependencies]
heck = "0.5.0"

The new line is heck = "0.5.0", under [dependencies]. That string is a version requirement: it allows later releases Cargo counts as compatible. Cargo.lock records the one chosen. Example 6 uses the crate.

Example 6. Using heck (b01-crate-demo/src/main.rs)

use heck::{ToKebabCase, ToSnakeCase};

fn main() {
    let event = "OrderShipped";
    println!("{event} -> {}", event.to_snake_case());
    println!("{event} -> {}", event.to_kebab_case());
}

Run from b01-crate-demo/, it prints:

OUTPUT
OrderShipped -> order_shipped
OrderShipped -> order-shipped

heck converts text between cases. The first line is the use from the previous section, with a path that starts at heck. After it, event.to_snake_case(), with event set to "OrderShipped", gives order_shipped, which is Str::snake()'s job in Laravel, and to_kebab_case() gives order-shipped.

You ran cargo add heck. Is there a vendor/heck folder in your project now? No. Cargo keeps downloaded crates in one cache, Cargo home, usually ~/.cargo. Your project has one new line in Cargo.toml and one new entry in Cargo.lock, and target/ holds only this project's build output. There is no vendor/ unless you run cargo vendor.

What should be pub?

So the demo runs, the private call is refused, and heck respelled OrderShipped twice. The lesson could end there. But look at what the defaults leave you with. Every item starts private, so every pub in the demo is a decision somebody made, and the compiler checks the decision without asking whether it was right. When you move a PHP namespace into Rust modules, which functions are the module's job, and which exist so the module can do its job? If a second module needed internal_rounding_rule, would you mark it pub, or move it? Who would you ask?

Testing

Without looking, draw the demo's module tree and mark which items are pub. Then check it against Examples 1 and 3 and src/billing/invoice.rs.

Before you build modules-demo/missing-mod and modules-demo/compile-fail, write down the error code you expect from each. The compiler's answers are in Examples 2 and 4.

You can get the file rules wrong a few times. The compiler names the module it couldn't find.

TL;DR

A package is described by one Cargo.toml and holds crates; a crate is what the compiler builds, rooted at src/main.rs or src/lib.rs; modules form a tree inside it. A mod line adds a file to that tree, and a file no mod line names is not compiled. Items are private to their module unless marked pub, and a use gives a shorter name without changing who may call what. std needs no Cargo.toml line; a crate from crates.io gets one from cargo add, its exact version goes in Cargo.lock, and its source lives in Cargo home, not in your project. Next: reading the compiler's messages in order.

¹ The layout here is the ordinary file-module one: billing.rs, with its child in billing/invoice.rs. A module can also be written inline, in braces inside its parent's file, or kept in billing/mod.rs. Neither is shown in this lesson.

² cargo add heck needs network access to crates.io. The output shown is from one recorded run.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 3
  • Rust Book [S20] ch. 7.1 "Packages and Crates", 7.2 "Defining Modules to Control Scope and Privacy", 7.3 "Paths", 7.4 "Bringing Paths into Scope with the use Keyword", 7.5 "Separating Modules into Different Files"; std docs [S24] "The Rust Prelude"; Error Codes Index [S63] E0433, E0603; PHP Manual [S27] "Namespaces"; PSR-4 [S67]
  • Cargo Book [S22] cargo add, "Cargo Home", "Specifying Dependencies"; heck 0.5.0 documentation [S23]
  • Composer docs [S28] "Command-line interface"; Laravel docs 13.x strings.md (Str::snake) [S3]. Books: TRPL 3rd ed. [S17] ch. 7 "Packages and Crates" 17.12, "Paths for Referring to an Item in the Module Tree" 17.14, "Bringing Paths into Scope with the use Keyword" 17.15, "Separating Modules into Different Files" 17.16, ch. 2 "Processing a Guess", ch. 1 "Hello, Cargo! > Building and Running a Cargo Project" 11.6 (Cargo.lock); Programming Rust 3rd ed. [S18] ch. 8 "Modules", ch. 8 "Specifying Dependencies" and "Specifying Dependencies > Cargo.lock"; Learn Rust in a Month of Lunches [S19] 14.1.1.

Rust Book: Packages and crates · Rust Book: Defining modules to control scope and privacy · Rust Book: Paths · Rust Book: The use keyword · Rust Book: Separating modules into different files · std: The Rust prelude · Error index: E0433 · Error index: E0603 · PHP Manual: Namespaces · PSR-4: Autoloader · Cargo Book: cargo add · Cargo Book: Cargo home · Cargo Book: Specifying dependencies · heck 0.5.0 documentation · Composer: Command-line interface · Laravel docs: Strings

NOT CHECKED — 9
  • The file layout shown, billing.rs with its child in billing/invoice.rs, is one of three. Inline modules and billing/mod.rs also exist and are not demonstrated.
  • Three answers come from the Rust Book and were not compiled for this lesson: that deleting pub mod invoice; takes invoice out of the program, that a child module can call its parent's private function, and that a use line cannot reach a private function.
  • Calling a module "the nearest thing to a PHP namespace" is this course's comparison, not a statement from either language's documentation.
  • That a package published on crates.io is called a crate is stated without a specific source passage.
  • That heck = "0.5.0" allows later compatible releases comes from the Cargo Book; the matching passage in Programming Rust was located but not read.
  • Cargo home, cargo add and cargo vendor are documented in the Cargo Book only; none of the three Rust books checked covers them, and the sentence about cargo vendor was not re-read against the Cargo Book.
  • The cargo add heck output was recorded once, with network access to crates.io, on cargo 1.100.0. With no version given, cargo add picks the newest release on crates.io that day, so a later run can pick a different one.
  • The Str::snake comparison comes from the Laravel documentation; no Laravel code was run.
  • Compiler messages and program output were recorded with rustc 1.100.0 and PHP 8.5.8.