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.2 · 11 min

Saving and loading

Close Chatterbox and the whole conversation is gone. A file on disk fixes that, and reading and writing it is one more thing that can fail, which is exactly what Result and ? are for.

Adds to ChatterboxThe history survives a restart.

Two functions and a file

The standard library's std::fs module has the two functions we need. fs::write(path, text) puts text in a file, replacing whatever was there. fs::read_to_string(path) gives the whole file back as a String. Both return a Result with an io::Error as the reason, because disks fill up, folders go missing and permissions say no.

Files hold text, but our history is a list of Message values. So we need two small translators: one that turns the list into lines of text, and one that turns lines back into the list. Each line looks like you: hello: the author, a colon and a space, then the message. That is exactly the line Message::to_line has made since lesson 5.2, so the file will read like a transcript.

These two functions touch no files, so you can test them anywhere, with plain strings and assert_eq!, exactly as in lesson 7.3. That is deliberate: keep the part that can be checked separate from the part that talks to the disk. Write them first as a warm-up, with a small Message of its own that has the same two fields, author and text. Chatterbox's own copies of the same two functions are in the new store.rs further down.

Three small things in the warm-up are new. history: &[Message] is a slice (lesson 4.6) of messages: a borrowed view of a list, so the function can read a Vec<Message>, or part of one, without taking it. #[derive(Debug, PartialEq)] asks the compiler for two abilities: PartialEq lets == compare two messages field by field (lesson 8.1), which is what from_lines(&text) == h in main relies on, and Debug lets assert_eq! print both sides when they differ. And print! is println! without the newline at the end, because each line already ends in one: , the newline character.

Try itWarm-up: history to text and back

Write to_lines (one line per message, like you: hello, each ending in a newline) and from_lines (the reverse). A line with no colon-and-space is skipped. split_once(": ") splits at the first colon-and-space only, so a message that itself contains a colon survives.

Write to_lines (one line per message, like you: hello, each ending in a newline) and from_lines (the reverse). A line with no colon-and-space is skipped. split_once(": ") splits at the first colon-and-space only, so a message that itself contains a colon survives.

#[derive(Debug, PartialEq)]
struct Message {
author: String,
text: String,
}
 
fn to_lines(history: &[Message]) -> String {
// one "author: text" line per message
String::new()
}
 
fn from_lines(s: &str) -> Vec<Message> {
// the reverse; skip lines you do not understand
Vec::new()
}
 
fn main() {
let h = vec![
Message { author: String::from("you"), text: String::from("hi") },
Message { author: String::from("bot"), text: String::from("hello!") },
];
let text = to_lines(&h);
print!("{text}");
println!("{}", from_lines(&text) == h);
}

Hidden tests (4): unknown_lines_are_skipped writes_one_line_per_message colon_inside_the_text_survives round_trip

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

Talking to the disk

Now the thin layer on top. Chatterbox gets a fourth file, store.rs, a module (lesson 8.1) with one job: the history on disk. Its first line, use crate::message::Message;, needs one new word. crate means "the top of this program", so the path reads "from the top, into the message module, the Message type". store sits beside message, not inside it, so it starts from the top.

  • FILE is a const: one fixed name, chatterbox.log, for the whole program. The file appears in whatever folder you run Chatterbox from.
  • to_lines and from_lines are the two translators from the warm-up, using to_line for the writing half. They stay private: only load and save are pub.
  • save is one line: translate, then fs::write.
  • load has one subtlety. The very first time Chatterbox runs there is no file, and that is not an error, it just means "no history yet". So it looks at the kind of error. A NotFound becomes an empty history; any other problem is handed back as an Err. The if after Err(e) is a guard: that arm only matches when its condition is true.

main returns a Result

In main.rs, main now returns Result<(), io::Error>, which is what lets ? work inside it (lesson 7.2). () means "nothing": on success main has nothing to hand back, and the last line, Ok(()), says exactly that.

That changes four places. The history starts as store::load(store::FILE)? instead of an empty Vec. After the greeting, if something was loaded, Chatterbox says how many messages it remembers. After the loop, store::save writes the history out and prints where it went; the line before that print, let s = if history.len() == 1 { "" } else { "s" };, picks the word ending, so one message reads "saved 1 message" and two read "saved 2 messages". And the two read_line(...).unwrap() calls become read_line(...)?. That last change is worth a moment. unwrap() on an Err stops the program on the spot with a crash message (a panic). With ?, the error is passed out of main instead: Rust prints it and the program exits, reporting failure. Now that main returns a Result, there is no reason to crash.

The history is saved when the loop ends, whether you typed /quit or the input simply ran out. If you force the program to stop (Ctrl+C in most terminals), the loop never ends normally and nothing is saved.

Chatterbox v0.8 after lesson 8.2: the whole program (green lines are new in this lesson)
src/main.rs15 new lines
// Chatterbox: a small chat program, built one lesson at a time.
mod command;
mod message;
mod store;
 
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() -> Result<(), io::Error> {
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> = store::load(store::FILE)?; // last time's conversation, if any
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)?;
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
if !history.is_empty() {
println!(
"(I remember {} messages from last time. /history shows them.)",
history.len()
);
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line)?;
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}");
store::save(store::FILE, &history)?;
let s = if history.len() == 1 { "" } else { "s" };
println!("saved {} message{s} to {}", history.len(), store::FILE);
Ok(())
}
 
// 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.rsunchanged
//! 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.rsunchanged
//! 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()
}
}
src/store.rsnew file
//! Saving the conversation to a file and reading it back.
use crate::message::Message;
use std::fs;
use std::io;
 
/// Where the history is kept, next to wherever you run Chatterbox.
pub const FILE: &str = "chatterbox.log";
 
/// The history as text, one "author: text" line per message.
fn to_lines(history: &[Message]) -> String {
let mut out = String::new();
for m in history {
out.push_str(&m.to_line());
out.push('\n');
}
out
}
 
/// Text in that format, back into messages. Lines that do not fit are skipped.
fn from_lines(text: &str) -> Vec<Message> {
let mut out = Vec::new();
for line in text.lines() {
if let Some((author, said)) = line.split_once(": ") {
out.push(Message::new(author, said));
}
}
out
}
 
/// The saved history, or an empty one the very first time (no file yet).
pub fn load(path: &str) -> Result<Vec<Message>, io::Error> {
match fs::read_to_string(path) {
Ok(text) => Ok(from_lines(&text)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(e) => Err(e),
}
}
 
/// Write the whole history to the file, replacing what was there.
pub fn save(path: &str, history: &[Message]) -> Result<(), io::Error> {
fs::write(path, to_lines(history))
}
You type
Sam
remember this
/quit
(run it again)
Sam
/history
/quit
Chatterbox prints (a real run)
Chatterbox v0.8
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: remember this
bot: bye, Sam!
messages so far: 1
saved 2 messages to chatterbox.log

--- next run ---
Chatterbox v0.8
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
(I remember 2 messages from last time. /history shows them.)
1. you: remember this
2. bot: you said: remember this
bot: bye, Sam!
messages so far: 0
saved 2 messages to chatterbox.log

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

That run is the same program started twice in the same folder. The first run talks, quits and saves 2 messages. The second run finds the file, says it remembers them, and /history shows them: they came back from the disk, not from memory. Note that messages so far counts only this run's messages, while the saved file keeps everything.

What you have now

Chatterbox remembers. Start it, talk, quit, start it again: the history is still there. Along the way you used Result to say what can fail, ? to pass failures up (now all the way out of main), a module of its own for the disk code, and a real file. Chapter 9 gives the bot something real to say back.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
Why is a missing log file handled differently from other io errors?Reveal
The first run has no file yet, which just means an empty history. Other errors (permissions, a broken disk) are real problems and are passed up.
Why does main return Result<(), io::Error>?Reveal
So ? can be used in main. A failed load, save or read then ends the program with the error printed, instead of a crash from unwrap() or being silently ignored.
Why keep to_lines and from_lines separate from the file functions?Reveal
They touch no disk, so they can be tested anywhere with plain strings.

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

Questions people ask

How do I read a file into a String in Rust?

Call std::fs::read_to_string with the file path. It returns a Result: Ok with the whole file as text, or Err with an io::Error if the file could not be read.

How do I write text to a file in Rust?

Call std::fs::write with the path and the text. It replaces anything already in the file and returns a Result, because writing to a disk can fail.

How do I check if a file was not found in Rust?

Look at the error kind: if e.kind() == io::ErrorKind::NotFound, the file does not exist. You can then treat it as empty instead of as a failure.

Why does my file not save in the Rust Playground?

The online Playground has no files that last between runs. Run the program on your own computer with cargo run to see the file appear.

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