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.
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.
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.
FILEis aconst: one fixed name,chatterbox.log, for the whole program. The file appears in whatever folder you run Chatterbox from.to_linesandfrom_linesare the two translators from the warm-up, usingto_linefor the writing half. They stay private: onlyloadandsavearepub.saveis one line: translate, thenfs::write.loadhas 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. ANotFoundbecomes an empty history; any other problem is handed back as anErr. TheifafterErr(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.
src/command.rsunchanged
src/message.rsunchanged
Sam remember this /quit (run it again) Sam /history /quit
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.
Say it out loud, then reveal
Why is a missing log file handled differently from other io errors?Reveal
Why does main return Result<(), io::Error>?Reveal
unwrap() or being silently ignored.Why keep to_lines and from_lines separate from the file functions?Reveal
That is lesson 8.2. Tick it off so the course remembers where you are.
Go deeper
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.