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.
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.rsholds theMessagestruct and its methods. The struct, both fields and all three methods are markedpub, becausemain.rsuses every one of them: it builds messages withMessage::new, prints them withto_line, and readsm.textandm.authorin/countand/find.command.rsholds everything about reading a line:Command,CommandErrorand itsDisplayblock, andparse. Only those three arepub. The helpersneed,parse_count,is_command,first_wordandargstay private: they are howparsedoes its job, and nothing outside the box needs them.CommandErrorhas to be public even thoughmainnever writes its name, because the publicparsehands one back.- The tests moved with the code they check. The five tests about
parsenow sit at the bottom ofcommand.rs, in its ownmod tests, joined by a new one for/remember. There,use super::*;means "everything incommand", private helpers included: a module's own tests are inside the box, so privacy does not keep them out. The two tests aboutreplystay inmain.rs, next toreply.cargo testfinds and runs both sets. main.rskeeps what is about the conversation itself:HELP,banner,greeting,replyand the chat loop. At the top,mod command;andmod message;pull in the two files, anduse 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.
Sam /help /quit
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.
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.
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.
Say it out loud, then reveal
What is the default visibility of an item inside a mod?Reveal
What does `mod message;` (with a semicolon) mean in main.rs?Reveal
What does use do?Reveal
That is lesson 8.1. Tick it off so the course remembers where you are.
Go deeper
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.
