Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 8: Organising code

Lesson 8.1 · 8 min

Splitting code into modules

Chatterbox is one file of almost 400 lines, and finding anything means scrolling. Rust lets you put related code in named boxes called modules, give each box its own file, and decide what each box shows to the rest of the program.

Adds to Chatterboxmessage.rs and command.rs split out of main.rs.

Compiler errors you will meet E0616

Boxes with a front door

Chatterbox now has a message type, a command parser, an error type and its tests. Everything sits in one long list in main.rs. You have already met one module without the full story: mod tests from lesson 7.3. A module is a named box around some of that code. Writing mod message { ... } creates a box called message.

The rule that makes boxes useful: everything inside is private by default. Code outside the box cannot see it. You choose what to show by writing pub (short for public) in front of it. That way message can keep its details to itself and only offer a small, stable surface.

Reaching into a private field
mod message {
pub struct Message {
text: String,
}
 
impl Message {
pub fn new(text: &str) -> Message {
Message { text: text.to_string() }
}
}
}
 
fn main() {
let m = message::Message::new("hi");
println!("{}", m.text);
}
error[E0616]: field `text` of struct `Message` is private
  --> src/main.rs:15:22
   |
15 |     println!("{}", m.text);
   |                      ^^^^ private field

The struct is pub, so main may name it and call new. The field text is not, so it is off limits. Two fixes: write pub text: String to show it, or add a pub fn text(&self) -> &str that shows it on your terms. The second keeps the freedom to change how the text is stored later.

Walking in with use

Outside a module you reach its items with a path: message::Message. Typing that every time gets tiring, so use message::Message; brings the name into scope once: from that line on, Message alone is enough.

From mod to file

A box can be written right inside main.rs as mod message { ... }, the way the example above does so it can run in your browser. In a real project the box usually gets its own file. Take what is inside the braces, put it in src/message.rs, and in main.rs write only mod message;, with a semicolon instead of braces. The semicolon form tells Rust "this module's contents are in the file with the same name". Nothing else changes: pub and use work exactly as before.

Cargo has no command that makes a module file for you; you make it yourself, next to main.rs. In a terminal, from the project folder:

touch src/message.rs src/command.rs

(touch makes an empty file on macOS and Linux. On Windows, or if you prefer, use your editor's "New File" in the src folder.) Then paste the code in, add the mod lines to main.rs, and run cargo run as always. Cargo finds a file through its mod line: a file in src/ that no mod line names is simply ignored.

chatterbox/
  Cargo.toml
  src/
    main.rs       // mod command; mod message; the chat loop
    message.rs    // Message
    command.rs    // Command, CommandError, parse

Chatterbox in three files

This is the split, done for real. No behaviour changes in this lesson: Chatterbox answers exactly as it did after lesson 7.4. What changes is where things live and what each file lets the others see.

  • message.rs holds the Message struct and its methods. The struct, both fields and all three methods are marked pub, because main.rs uses every one of them: it builds messages with Message::new, prints them with to_line, and reads m.text and m.author in /count and /find.
  • command.rs holds everything about reading a line: Command, CommandError and its Display block, and parse. Only those three are pub. The helpers need, parse_count, is_command, first_word and arg stay private: they are how parse does its job, and nothing outside the box needs them. CommandError has to be public even though main never writes its name, because the public parse hands one back.
  • The tests moved with the code they check. The five tests about parse now sit at the bottom of command.rs, in its own mod tests, joined by a new one for /remember. There, use super::*; means "everything in command", private helpers included: a module's own tests are inside the box, so privacy does not keep them out. The two tests about reply stay in main.rs, next to reply. cargo test finds and runs both sets.
  • main.rs keeps what is about the conversation itself: HELP, banner, greeting, reply and the chat loop. At the top, mod command; and mod message; pull in the two files, and use command::{Command, parse}; brings two names in at once (the braces list them).

A comment that starts with //!, like the first line of each new file, describes the whole file it sits in rather than the line below it.

Chatterbox v0.8 after lesson 8.1: the whole program (green lines are new in this lesson)
src/main.rs6 new lines
// Chatterbox: a small chat program, built one lesson at a time.
mod command;
mod message;
 
use command::{Command, parse};
use message::Message;
use std::collections::HashMap;
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 8);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /stats, /remember <name> <fact>, /recall <name>, /find <word>, /last <n>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {name}! I'm {BOT}.");
text.push_str(" Ask me anything.");
text
}
 
/// What the bot says back to an ordinary message (not a command).
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {MAX_LEN} bytes)")
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {message}")
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = Vec::new(); // everything said so far, in order
let mut facts: HashMap<String, String> = HashMap::new(); // name -> fact, for /recall
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
let cmd = match parse(message) {
Ok(cmd) => cmd,
Err(e) => {
println!("bot: {e}");
continue;
}
};
match cmd {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {name}!");
break;
}
Command::Help => println!("bot: {HELP}"),
Command::Again => {
if let Some(text) = &last {
println!("bot: {}", reply(text));
} else {
println!("bot: nothing to repeat yet");
}
}
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let bytes: usize = history.iter().map(|m| m.text.len()).sum();
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Stats => {
// One chain of steps: your messages -> their words -> a count per word.
let mut counts: HashMap<String, u32> = HashMap::new();
for word in history
.iter()
.filter(|m| m.author == "you")
.flat_map(|m| m.text.split_whitespace())
{
*counts.entry(word.to_lowercase()).or_insert(0) += 1;
}
let mut top: Vec<(String, u32)> = counts.into_iter().collect();
// most used first; ties in alphabetical order, so the answer never changes
top.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let words: Vec<String> = top
.iter()
.take(3)
.map(|(word, n)| format!("{word} ({n})"))
.collect();
if words.is_empty() {
println!("bot: nothing said yet");
} else {
println!("bot: your top words: {}", words.join(", "));
}
}
Command::Remember(key, fact) => {
println!("bot: got it: {key} is {fact}");
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {key} is {fact}"),
None => println!("bot: I don't know anything about {key}"),
},
Command::Recall(None) => {
if facts.is_empty() {
println!("bot: I don't remember anything yet. Try /remember");
} else {
// A HashMap has no order, so sort the names before printing them.
let mut names = Vec::new();
for name in facts.keys() {
names.push(name.as_str());
}
names.sort();
println!("bot: I remember: {}", names.join(", "));
}
}
Command::Find(word) => {
// The closure borrows `word` from here: a small function made on the spot.
let hits: Vec<&Message> = history
.iter()
.filter(|m| m.author == "you" && m.text.contains(&word))
.collect();
if hits.is_empty() {
println!("bot: you never said {word}");
} else {
for m in hits {
println!("{}", m.to_line());
}
}
}
Command::Last(n) => {
// Start n messages from the end, or at the beginning if there are fewer.
let start = if n >= history.len() {
0
} else {
history.len() - n
};
for m in &history[start..] {
println!("{}", m.to_line());
}
}
Command::Say(text) => println!("bot: {text}"),
Command::Shout(text) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Debug(text) => println!("bot: {:?}", parse(&text)),
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
println!("bot: {}", answer.text);
history.push(said);
history.push(answer);
// Message::new made the history its own copy, so `text` itself can
// be handed to `last` for /again: no extra copy needed.
last = Some(text);
}
}
}
println!("messages so far: {messages_seen}");
}
 
// Tests: `cargo test` builds and runs them; the program itself never sees them.
#[cfg(test)]
mod tests {
use super::*;
 
#[test]
fn reply_echoes_and_answers_questions() {
assert_eq!(reply("hi"), "you said: hi");
assert!(reply("are you there?").starts_with("Good question!"));
}
 
#[test]
fn reply_refuses_long_messages() {
let long = "x".repeat(MAX_LEN + 1);
assert!(reply(&long).starts_with("that is too long"));
}
}
src/command.rsnew file
//! Commands: what a line of input means, and what can be wrong with it.
use std::fmt;
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
pub enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Stats,
Remember(String, String),
Recall(Option<String>),
Find(String),
Last(usize),
Say(String),
Shout(String),
Debug(String),
Chat(String),
}
 
/// Everything that can be wrong with a line of input. parse() returns one of
/// these instead of a Command, and main prints it.
#[derive(Debug)]
pub enum CommandError {
Unknown(String),
Missing(String, String),
Usage(String),
NotACount(String),
}
 
/// How a CommandError reads when printed with {}.
impl fmt::Display for CommandError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CommandError::Unknown(word) => {
write!(f, "I don't know the command {word}. Try /help.")
}
CommandError::Missing(verb, example) => {
write!(f, "{verb} what? Try /{verb} {example}")
}
CommandError::Usage(form) => write!(f, "try {form}"),
CommandError::NotACount(text) => write!(f, "'{text}' is not a count. Try /last 3"),
}
}
}
 
/// The text after a command word, or the error that says it is missing.
fn need(line: &str, verb: &str, example: &str) -> Result<String, CommandError> {
match arg(line) {
Some(text) => Ok(String::from(text)),
None => Err(CommandError::Missing(
String::from(verb),
String::from(example),
)),
}
}
 
/// How many messages /last should show. "two" or "-1" is an error.
fn parse_count(text: &str) -> Result<usize, CommandError> {
match text.parse::<usize>() {
Ok(n) => Ok(n),
Err(_) => Err(CommandError::NotACount(String::from(text))),
}
}
 
/// Turn one line of input into a Command, or say what is wrong with it.
/// Each `?` means: if this step failed, return its error right here.
pub fn parse(line: &str) -> Result<Command, CommandError> {
let cmd = match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
"/stats" => Command::Stats,
"/remember" => {
let usage = CommandError::Usage(String::from("/remember <name> <fact>"));
let rest = match arg(line) {
Some(rest) => rest,
None => return Err(usage),
};
match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => return Err(usage),
}
}
"/recall" => match arg(line) {
Some(name) => Command::Recall(Some(String::from(name))),
None => Command::Recall(None),
},
"/find" => Command::Find(need(line, "find", "hello")?),
"/last" => Command::Last(parse_count(&need(line, "last", "3")?)?),
"/debug" => Command::Debug(need(line, "debug", "/say hi")?),
"/say" => Command::Say(need(line, "say", "hello")?),
"/shout" => Command::Shout(need(line, "shout", "hello")?),
word => {
if is_command(word) {
return Err(CommandError::Unknown(String::from(word)));
}
Command::Chat(String::from(line))
}
};
Ok(cmd)
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
#[cfg(test)]
mod tests {
use super::*;
 
#[test]
fn plain_text_is_chat() {
assert!(matches!(parse("hello there"), Ok(Command::Chat(t)) if t == "hello there"));
}
 
#[test]
fn help_has_a_short_form() {
assert!(matches!(parse("/help"), Ok(Command::Help)));
assert!(matches!(parse("/h"), Ok(Command::Help)));
}
 
#[test]
fn say_needs_text() {
assert_eq!(
parse("/say").unwrap_err().to_string(),
"say what? Try /say hello"
);
}
 
#[test]
fn last_needs_a_number() {
assert!(matches!(parse("/last 3"), Ok(Command::Last(3))));
assert_eq!(
parse("/last two").unwrap_err().to_string(),
"'two' is not a count. Try /last 3"
);
}
 
#[test]
fn unknown_commands_are_errors() {
assert_eq!(
parse("/dance").unwrap_err().to_string(),
"I don't know the command /dance. Try /help."
);
}
 
#[test]
fn remember_takes_a_name_and_a_fact() {
assert!(
matches!(parse("/remember pizza extra cheese"), Ok(Command::Remember(k, v)) if k == "pizza" && v == "extra cheese")
);
assert!(parse("/remember pizza").is_err());
}
}
src/message.rsnew file
//! A Message: one line of the conversation.
 
/// One line of the conversation: who said it, and what they said.
pub struct Message {
pub author: String,
pub text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
pub fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
pub fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
pub fn shout(&self) -> String {
self.text.to_uppercase()
}
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "0.8.0"
edition = "2024"
 
[dependencies]
You type
Sam
/help
/quit
Chatterbox prints (a real run)
Chatterbox v0.8
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: commands: /help, /again, /history, /count, /stats, /remember <name> <fact>, /recall <name>, /find <word>, /last <n>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)
bot: bye, Sam!
messages so far: 0

Download this version (zip)Unzip, then cargo run inside the folder.

Notice how short main.rs got, and that the run is the same as before. That is what a good split looks like: the program does not notice, and the next person to open command.rs finds everything about commands in one place. The download has all three files in the right folders.

Try itYour turn: fill a command module

A small separate module to practise mod and pub on (simpler than Chatterbox's own parse, which returns a Result). Finish command::parse. /help and /quit give their variants, /last N gives Last(N) when N is a number, and everything else (including /last x) gives None. Use strip_prefix, which returns the rest of the text if the prefix is there. One new line in the starter: #[derive(Debug, PartialEq)] asks the compiler to write two abilities for Command. Debug is the {:?} form from lesson 5.5; PartialEq lets == compare two values of the type, which the tests need to check that parse gave the right command.

A small separate module to practise mod and pub on (simpler than Chatterbox's own parse, which returns a Result). Finish command::parse. /help and /quit give their variants, /last N gives Last(N) when N is a number, and everything else (including /last x) gives None. Use strip_prefix, which returns the rest of the text if the prefix is there. One new line in the starter: #[derive(Debug, PartialEq)] asks the compiler to write two abilities for Command. Debug is the {:?} form from lesson 5.5; PartialEq lets == compare two values of the type, which the tests need to check that parse gave the right command.

mod command {
#[derive(Debug, PartialEq)]
pub enum Command {
Help,
Quit,
Last(u32),
}
 
pub fn parse(line: &str) -> Option<Command> {
// /help, /quit, "/last N", else None
None
}
}
 
fn main() {
println!("{:?}", command::parse("/last 3"));
println!("{:?}", command::parse("hello"));
}

Hidden tests (4): last_with_a_number help_and_quit last_with_junk_is_none plain_text_is_none

This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.

What you have now

Chatterbox is three files, and each of its two modules shows the rest of the program only what it needs. As a preview, the next lesson adds a fourth file, store.rs, that writes the history to disk so it is still there tomorrow.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is the default visibility of an item inside a mod?Reveal
Private: only code inside the module can use it. Add pub to expose it.
What does `mod message;` (with a semicolon) mean in main.rs?Reveal
The contents of module message live in the file src/message.rs.
What does use do?Reveal
It brings a name into scope so you do not have to write its full path each time.

That is lesson 8.1. Tick it off so the course remembers where you are.

Questions people ask

What is a module in Rust?

A module is a named box around related code, made with mod. Everything inside it is private unless marked pub, so each module chooses what the rest of the program can see.

How do I split Rust code into multiple files?

Move the body of mod message { ... } into src/message.rs, and leave the single line mod message; in main.rs. Rust then reads that module from the file with the same name.

Is there a cargo command that creates a module file?

No. Create the file yourself in the src folder, for example src/command.rs, and add the line mod command; to main.rs. Cargo only compiles files that a mod line names.

What does pub mean in Rust?

pub is short for public. It lets code outside the module use the item; without it, the item is private to its module.

What does error E0616 mean in Rust?

You tried to read a struct field that is private to its module. Mark the field pub, or add a pub method that returns it.

Learn Rust by building a chat app · Lesson 8.1 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026