17 / 35

Rust for the Web· 9 min read· Lesson 17 of 35

Modules and Crates

Part 1 · Rust. Organise Rust code into modules and files, control what is public with pub, and add outside crates like serde through Cargo.toml.

A tiny café can keep everything on one counter. A growing café needs shelves: one for the menu, one for orders, one for stock. In Rust, those shelves are called modules, and sharing code with the wider world happens through crates. This lesson covers both, because every web project you will ever open is built from them.

Modules: shelves inside your program

A module groups related code under a name. You create one with mod:

src/main.rs
mod menu {
pub struct Item {
pub name: String,
pub price_cents: u32,
}
pub fn latte() -> Item {
Item { name: String::from("Latte"), price_cents: 450 }
}
}
fn main() {
let item = menu::latte();
println!("{} costs {} cents", item.name, item.price_cents);
}
Output
Latte costs 450 cents
  1. mod menu { ... } creates a module named menu.
  2. Inside it we define a struct and a function.
  3. From outside we reach things with a path: menu::latte(). The :: reads as “inside”.

pub: who may touch this?

Everything in Rust is private by default: code outside the module cannot use it. Add pub (short for public) to open it up. In the example, pub struct Item, each pub field, and pub fn latte are all needed. If we remove pub from latte, the compiler says:

Output
error[E0603]: function `latte` is private

That message means exactly what it says. Add pub and it works.

Warning

Making a struct pub does not make its fields pub. A struct whose fields are private cannot be built with Item { ... } from outside its module. Mark each field you want to expose.

Private by default is a feature: it lets a module hide its inner workings so you can change them later without breaking everything else. You will also see pub(crate), which means “public inside this project, but not to outsiders.”

use: shortcuts for long paths

Typing menu::latte() everywhere gets tiring. use brings a name into scope:

use menu::latte;
fn main() {
let item = latte();
println!("{}", item.name);
}

You can pull several names with braces: use menu::{latte, Item};. You have been using use already, for example use std::collections::HashMap;.

Glob imports and preludes

Sometimes a module has so many useful names that importing them one by one gets tedious. The glob import * brings in everything public from a module at once:

src/main.rs
mod menu {
pub struct Item {
pub name: String,
pub price_cents: u32,
}
pub fn latte() -> Item {
Item { name: String::from("Latte"), price_cents: 450 }
}
// A "prelude": the handy names, gathered in one place
pub mod prelude {
pub use super::{latte, Item};
}
}
use menu::prelude::*;
fn main() {
let item: Item = latte();
println!("{} costs {} cents", item.name, item.price_cents);
}
Output
Latte costs 450 cents

A prelude is a module that exists only to be glob-imported: its author re-exports (pub use) the most commonly needed names, so users write one line, use some_crate::prelude::*;, instead of ten. Rust has one built in, which is why you can use Vec, String, Option and Some without importing anything. Frameworks copy the idea. Laravel Rust code typically starts with use laravel::prelude::*;.

Tip

Globs are great for preludes, but use them sparingly elsewhere: with use something::*; it is harder to see where a name came from.

Files are modules

Putting everything in one file defeats the purpose. Rust lets a file be a module. Suppose our project looks like this:

Output
rusty-bean/
├── Cargo.toml
└── src/
├── main.rs
├── menu.rs
└── orders.rs

In src/main.rs you declare the modules:

src/main.rs
mod menu;
mod orders;
fn main() {
let item = menu::latte();
println!("{}", orders::describe(&item));
}

And each file holds the contents without the mod { } wrapper:

src/menu.rs
pub struct Item {
pub name: String,
pub price_cents: u32,
}
pub fn latte() -> Item {
Item { name: String::from("Latte"), price_cents: 450 }
}
src/orders.rs
use crate::menu::Item;
pub fn describe(item: &Item) -> String {
format!("1 x {} ({} cents)", item.name, item.price_cents)
}

Walk through it:

  1. mod menu; with a semicolon tells Rust: “look for src/menu.rs and treat it as the menu module.”
  2. crate:: in a path means “start from the top of this project.” That is how orders.rs finds menu.
  3. Each file only exposes what is marked pub.

Important

A file is only part of your program if some mod name; line declares it. Creating src/orders.rs without mod orders; in main.rs does nothing; Rust will not even look at it.

For bigger groups, a folder works too: src/menu/mod.rs (or src/menu.rs plus a src/menu/ folder) holds a module with its own sub-modules.

Crates: packages of code

A crate is a unit of Rust code that compiles together. Your project is a crate. A library crate is code made for others to use. Rust’s package manager, Cargo, downloads library crates from crates.io, the public shelf where the community shares them.

You list what you need under [dependencies] in Cargo.toml:

Cargo.toml
[package]
name = "rusty-bean"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
  1. serde is the crate that turns Rust values into formats like JSON and back. version = "1" means “any 1.x version.”
  2. features = ["derive"] switches on an optional part of the crate: the #[derive(Serialize, Deserialize)] helpers. Features are like add-on options in a coffee order.
  3. serde_json adds the JSON format itself.

You can also add a crate from the terminal:

Terminal window
cargo add serde --features derive
cargo add serde_json

Package names may contain hyphens, like rusty-bean. In your code, Cargo turns the hyphens into underscores, so a crate called my-cafe is written my_cafe in a use line.

The next cargo build or cargo run downloads and compiles them. Cargo also writes Cargo.lock, which records the exact versions so every machine builds the same thing.

Using serde

src/main.rs
use serde::Serialize;
#[derive(Serialize)]
struct Item {
name: String,
price_cents: u32,
}
fn main() {
let item = Item { name: String::from("Latte"), price_cents: 450 };
let json = serde_json::to_string(&item).unwrap();
println!("{}", json);
}
Output
{"name":"Latte","price_cents":450}
  1. use serde::Serialize; imports the trait from the crate, just like a module path.
  2. #[derive(Serialize)] is a derive from the traits lesson. It writes the code that knows how to turn Item into JSON.
  3. serde_json::to_string(&item) returns a Result. We use .unwrap() to keep the demo short; real code would handle the error with ?.

Tip

Not sure which crate you need? Search on crates.io (opens in new tab) and check the download count and recent updates. The “Documentation” link goes to docs.rs, where every crate’s API is documented.

Why this matters for web code

Web apps return JSON, read forms, talk to databases and send emails. Almost none of that is written from scratch; it comes from crates. Laravel Rust itself is a collection of crates built on top of Axum and Tokio. A Laravel Rust project has a Cargo.toml listing dependencies and a src/ folder split into modules, such as one module for handlers and another for models, so everything you learned here will look familiar.

Try it yourself

  1. Create a module stock with a public function low_stock(count: u32) -> bool that returns true when count < 5. Call it from main.
  2. In a new project, add serde and serde_json, then serialize a Customer { name, loyalty_points } to JSON.
Show solution
src/main.rs
mod stock {
pub fn low_stock(count: u32) -> bool {
count < 5
}
}
fn main() {
println!("{}", stock::low_stock(3));
}
Output
true

For the second exercise, the dependencies go in Cargo.toml (as before, or via cargo add serde --features derive and cargo add serde_json):

Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

And the full program:

src/main.rs
use serde::Serialize;
#[derive(Serialize)]
struct Customer {
name: String,
loyalty_points: u32,
}
fn main() {
let customer = Customer { name: String::from("Maya"), loyalty_points: 120 };
let json = serde_json::to_string(&customer).unwrap();
println!("{}", json);
}
Output
{"name":"Maya","loyalty_points":120}

Recap

  • A module (mod) groups code; everything is private until marked pub.
  • use creates shortcuts; crate:: starts a path at the top of the project.
  • A file becomes a module when main.rs declares mod filename;.
  • A crate is a package of Rust code; crates.io is where Cargo downloads them.
  • Dependencies live in Cargo.toml; features switch on optional parts, like serde’s derive.

What’s next

You have now seen #[derive(Serialize)] and println! several times. Time to understand what those # and ! things really are in Macros and Attributes.

0 of 35 lessons complete

Search lessons

Type to search all lessons.