Rust Playbook

Course › Week 2 · Errors, collections, traits › Day 1 · lesson 8 of 42 · 15 min reading + 60 min practice

Modules and project layout

Split a program into lib.rs, main.rs and files, and control what is public.

modpubuselib.rscrates

On this page
  1. 1. mod: a named group of code
  2. 2. Everything is private until marked pub
  3. 3. One module per file
  4. 4. use: shorter paths
  5. 5. A pub struct can still have private fields
  6. 6. lib.rs and main.rs in one package
  7. Coming from PHP
  8. Practice
  9. Remember

logstat is one 150-line file. That is fine for a day, and it is how every project starts, but by the end of this week it will have flags, an error type, a report and tests. Today you learn how Rust splits a program into parts.

In PHP, a namespace plus Composer’s PSR-4 autoloader decide where a class lives: put App\Log\Level in app/Log/Level.php and it is found. Rust has no autoloader. You declare the tree of modules yourself, and only what you declare is compiled.

1. mod: a named group of code

A module is declared with mod and a block. Code outside reaches into it with ::, the way PHP uses \ between namespace parts.

src/main.rs
mod level {
    pub enum Level {
        Info,
        Error,
    }

    pub fn parse(name: &str) -> Option<Level> {
        match name {
            "INFO" => Some(Level::Info),
            "ERROR" => Some(Level::Error),
            _ => None,
        }
    }
}

fn main() {
    match level::parse("ERROR") {
        Some(level::Level::Error) => println!("an error"),
        Some(level::Level::Info) => println!("info"),
        None => println!("unknown"),
    }
}
$ cargo run
an error

match can look inside an Option: Some(level::Level::Error) matches only that variant inside Some.

2. Everything is private until marked pub

In PHP, a class method is public unless you write private. In Rust it is the other way round: an item inside a module can only be used inside that module, unless it is marked pub.

src/main.rsdoes not compile
mod level {
    pub enum Level {
        Info,
        Error,
    }

    fn parse(name: &str) -> Option<Level> {
        match name {
            "INFO" => Some(Level::Info),
            "ERROR" => Some(Level::Error),
            _ => None,
        }
    }
}

fn main() {
    match level::parse("ERROR") {
        Some(_) => println!("a level"),
        None => println!("unknown"),
    }
}
cargo build
error[E0603]: function `parse` is private
  --> src/main.rs:17:18
   |
17 |     match level::parse("ERROR") {
   |                  ^^^^^ private function
   |
note: the function `parse` is defined here
  --> src/main.rs:7:5
   |
 7 |     fn parse(name: &str) -> Option<Level> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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

Private by default means a module’s public items are exactly its contract. Anything not marked pub you can rename or delete without breaking another file.

3. One module per file

Move the module’s body into src/level.rs, and leave only mod level; (with a semicolon) in main.rs. The semicolon means “the body is in the file with this name”. Nothing else changes: the code still reaches it as level::parse.

src/level.rs
pub enum Level {
    Info,
    Warning,
    Error,
}

pub fn parse(name: &str) -> Option<Level> {
    match name {
        "INFO" => Some(Level::Info),
        "WARNING" => Some(Level::Warning),
        "ERROR" => Some(Level::Error),
        _ => None,
    }
}

pub fn label(level: &Level) -> &'static str {
    match level {
        Level::Info => "info",
        Level::Warning => "warning",
        Level::Error => "error",
    }
}
src/main.rs
mod level;

fn main() {
    for name in ["ERROR", "INFO", "EROR"] {
        match level::parse(name) {
            Some(found) => println!("{name}: {}", level::label(&found)),
            None => println!("{name}: unknown"),
        }
    }
}
$ cargo run
ERROR: error
INFO: info
EROR: unknown

&'static str in label is a reference to text that lives for the whole program: the string literals built into the binary. Day 5 explains the 'static; read it as “a text literal” for now.

A file that no mod declares is not compiled

This is the trap for a PHP developer. Create src/level.rs and use it without mod level;, and Rust does not even look at the file:

src/main.rsdoes not compile
fn main() {
    match level::parse("ERROR") {
        Some(found) => println!("{}", level::label(&found)),
        None => println!("unknown"),
    }
}
cargo build
error[E0433]: cannot find module or crate `level` in this scope
 --> src/main.rs:2:11
  |
2 |     match level::parse("ERROR") {
  |           ^^^^^ use of unresolved module or unlinked crate `level`
  |
help: to make use of source file src/level.rs, use `mod level` in this file to declare the module
  |
1 + mod level;
  |

error[E0433]: cannot find module or crate `level` in this scope
 --> src/main.rs:3:39
  |
3 |         Some(found) => println!("{}", level::label(&found)),
  |                                       ^^^^^ use of unresolved module or unlinked crate `level`
  |
help: to make use of source file src/level.rs, use `mod level` in this file to declare the module
  |
1 + mod level;
  |

For more information about this error, try `rustc --explain E0433`.
error: could not compile `hello` (bin "hello") due to 2 previous errors

The compiler noticed the file and names the missing line: mod level;. In a PHP project the file would simply have been autoloaded; here, until a mod line declares it, it is not part of the program.

4. use: shorter paths

use brings a name into scope so you can write it without its path, like PHP’s use App\Log\Level;. Paths start from one of three places: crate:: (the root of your own package), a module next to you, or another crate such as std::.

src/main.rs
mod level;

use crate::level::{Level, label, parse};

fn describe(found: Option<Level>) -> &'static str {
    match found {
        Some(level) => label(&level),
        None => "unknown",
    }
}

fn main() {
    println!("{}", describe(parse("WARNING")));
    println!("{}", describe(parse("NOTICE")));
}
$ cargo run
warning
unknown

The braces import several names from one module. The convention: import types (Level, HashMap) by name, and functions through their module (level::parse), so a reader sees where a function comes from. This example imports both ways to show the syntax.

5. A pub struct can still have private fields

pub on a struct makes the type visible. Each field needs its own pub. A private field can only be set and read inside the module, which is how a struct protects its own rules:

src/main.rsdoes not compile
mod stats {
    pub struct Counts {
        errors: u64,
    }

    impl Counts {
        pub fn new() -> Counts {
            Counts { errors: 0 }
        }

        pub fn add_error(&mut self) {
            self.errors += 1;
        }
    }
}

fn main() {
    let mut counts = stats::Counts::new();
    counts.add_error();
    println!("{}", counts.errors);
}
cargo build
error[E0616]: field `errors` of struct `Counts` is private
  --> src/main.rs:20:27
   |
20 |     println!("{}", counts.errors);
   |                           ^^^^^^ private field

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

The fix is a public method pub fn errors(&self) -> u64, a getter. Now nothing outside the module can set errors to a wrong number; it can only grow through add_error. That is a PHP class with a private int $errors and a getter, enforced the same way.

6. lib.rs and main.rs in one package

A package can hold a library (src/lib.rs) and a binary (src/main.rs) at the same time. The library holds the logic; the binary is a thin layer that reads arguments and prints. The binary uses the library by the package’s name, like any other crate.

This is the shape real tools have, and the one logstat takes on Day 6: the logic in the library can be tested directly, and later called from other Rust code, while main.rs stays short.

src/lib.rs
pub mod level;

/// The level of a Laravel log line, if it is an entry's first line.
pub fn entry_level(line: &str) -> Option<level::Level> {
    let close = line.find("] ")?;
    let rest = &line[close + 2..];
    let dot = rest.find('.')?;
    let colon = rest.find(": ")?;
    level::parse(&rest[dot + 1..colon])
}
src/main.rs
use logstat::entry_level;
use logstat::level;

fn main() {
    let line = "[2026-11-30 09:41:03] production.ERROR: Deadlock";

    match entry_level(line) {
        Some(found) => println!("{}", level::label(&found)),
        None => println!("not an entry"),
    }
}
$ cargo run
error

In main.rs, the library is called by the package name from Cargo.toml, here logstat (a - in a package name becomes _). Inside lib.rs itself, its own modules are reached with crate::.

Where files go

You writeRust looks for
mod level; in main.rs or lib.rssrc/level.rs
mod line; inside src/parse.rssrc/parse/line.rs
pub mod level; in lib.rssrc/level.rs, and it is visible to main.rs

You may see src/parse/mod.rs in older code: it is the previous style for the same thing. New code uses src/parse.rs next to a src/parse/ folder.

Coming from PHP

Composer’s PSR-4 autoloader maps namespaces to folders, and loads a class the first time it is used:

composer.json (part)
{
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

So in PHP the folder structure is the module structure, found at runtime. In Rust the mod lines are the structure, checked at compile time: a file nobody declares is ignored, a missing file is a compile error, and visibility is decided per item with pub. There is no equivalent of PHP’s “public by default”.

PracticeThe Book ch. 7, Rustlings modules, and split logstat

Read chapter 7 of the Book.

In Rustlings: 10_modules.

Exercise: split logstat v1

Take your Day 6 logstat and split it: src/level.rs for Level and parse_level, src/lib.rs for entry_level and Counts, and src/main.rs for reading the file and printing. Make public only what main.rs needs. Run it on the sample log: the output must not change.

Day 6 of this week starts from this layout, so keep the result.

Remember

  • Only what a mod line declares is compiled; everything is private until marked pub.
  • Put the logic in lib.rs and keep main.rs to reading input and printing output.

Tomorrow: Vec, String and HashMap, the three collections you will use every day.