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:
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);}Latte costs 450 centsmod menu { ... }creates a module namedmenu.- Inside it we define a struct and a function.
- 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:
error[E0603]: function `latte` is privateThat 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:
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);}Latte costs 450 centsA 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:
rusty-bean/├── Cargo.toml└── src/ ├── main.rs ├── menu.rs └── orders.rsIn src/main.rs you declare the modules:
mod menu;mod orders;
fn main() { let item = menu::latte(); println!("{}", orders::describe(&item));}And each file holds the contents without the mod { } wrapper:
pub struct Item { pub name: String, pub price_cents: u32,}
pub fn latte() -> Item { Item { name: String::from("Latte"), price_cents: 450 }}use crate::menu::Item;
pub fn describe(item: &Item) -> String { format!("1 x {} ({} cents)", item.name, item.price_cents)}Walk through it:
mod menu;with a semicolon tells Rust: “look forsrc/menu.rsand treat it as themenumodule.”crate::in a path means “start from the top of this project.” That is howorders.rsfindsmenu.- 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:
[package]name = "rusty-bean"version = "0.1.0"edition = "2024"
[dependencies]serde = { version = "1", features = ["derive"] }serde_json = "1"serdeis the crate that turns Rust values into formats like JSON and back.version = "1"means “any 1.x version.”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.serde_jsonadds the JSON format itself.
You can also add a crate from the terminal:
cargo add serde --features derivecargo add serde_jsonPackage 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
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);}{"name":"Latte","price_cents":450}use serde::Serialize;imports the trait from the crate, just like a module path.#[derive(Serialize)]is a derive from the traits lesson. It writes the code that knows how to turnIteminto JSON.serde_json::to_string(&item)returns aResult. 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
- Create a module
stockwith a public functionlow_stock(count: u32) -> boolthat returnstruewhencount < 5. Call it frommain. - In a new project, add
serdeandserde_json, then serialize aCustomer { name, loyalty_points }to JSON.
Show solution
mod stock { pub fn low_stock(count: u32) -> bool { count < 5 }}
fn main() { println!("{}", stock::low_stock(3));}trueFor the second exercise, the dependencies go in Cargo.toml (as before, or via cargo add serde --features derive and cargo add serde_json):
[dependencies]serde = { version = "1", features = ["derive"] }serde_json = "1"And the full program:
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);}{"name":"Maya","loyalty_points":120}Recap
- A module (
mod) groups code; everything is private until markedpub. usecreates shortcuts;crate::starts a path at the top of the project.- A file becomes a module when
main.rsdeclaresmod 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’sderive.
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