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.4 · 12 min

One name for anything that replies

Today Chatterbox answers with an echo. In the next chapter a real model will answer instead, and the chat loop should not care which. A trait is how Rust says "anything that can reply". With one, Chatterbox gets a /model command that swaps who answers while you chat.

Adds to ChatterboxA Replier trait, and /model to swap who answers.

A promise with a name

Right now the bot's answer comes from a function called reply in main.rs: it echoes your words. In the next chapter the answer will come from a real model over the internet. A chat loop that says "call the echo function" would have to be rewritten for the model. A chat loop that says "ask whatever replies" would not.

A trait is a list of things a type can do, with a name. It is a promise: any type that implements the trait has these methods. Chatterbox's trait is called Replier and promises two methods:

  • name(&self) -> &str: a short name, like echo, for the banner and for /model.
  • reply(&self, history: &[Message]) -> String: the answer to the conversation so far. It is handed the whole history as &[Message], a borrowed view of a list, the way &str is a borrowed view of text (lesson 8.3 used &[T]). Here the list is the history Vec, with the newest message last. The echo only looks at the last message, but a real model needs all of it, so the promise says so from the start.

Inside the trait block each method is only a first line ending in ;, with no body. The trait says what; each type that implements it says how.

The ability a generic can ask for

In lesson 8.3, last_n<T> worked for any T at all, because it never asked a T to do anything: it only counted and sliced. Most generic code is not that lucky. A function that wants to ask something for a reply needs a T that can reply. A trait is how it says so: T: Replier reads "any type T, as long as T keeps the Replier promise". That extra condition is called a trait bound. Here is a small example, separate from Chatterbox, with two types that keep the promise and one generic function that uses it.

PredictOne function, two kinds of replier
trait Replier {
fn name(&self) -> &str;
fn reply(&self, msg: &str) -> String;
}
 
struct Echo;
struct Pretend;
 
impl Replier for Echo {
fn name(&self) -> &str {
"echo"
}
fn reply(&self, msg: &str) -> String {
format!("you said: {msg}")
}
}
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
fn reply(&self, msg: &str) -> String {
format!("(pretend model) I read: {msg}")
}
}
 
// Any T at all, as long as T can reply.
fn ask<T: Replier>(r: &T, msg: &str) -> String {
format!("{} -> {}", r.name(), r.reply(msg))
}
 
fn main() {
println!("{}", ask(&Echo, "hi"));
println!("{}", ask(&Pretend, "hi"));
}

What is the second line this program prints?

  • pretend -> (pretend model) I read: hi
  • echo -> you said: hi
  • pretend -> you said: hi
Reveal the answer

The program prints: pretend -> (pretend model) I read: hi The second call hands ask a Pretend, so T is Pretend and both r.name() and r.reply(msg) run Pretend's own versions. Inside ask, the bound is what made those two calls allowed at all.

Read impl Replier for Echo as "here is how Echo keeps the promise". Now hand a function something that never made the promise. A function can also accept "anything that implements Replier" by taking &dyn Replier, a borrow of some replier whose exact type is not fixed. Either way, the compiler checks the promise.

PredictA type with no promise
trait Replier {
fn reply(&self, msg: &str) -> String;
}
 
struct Mute;
 
fn talk(r: &dyn Replier, msg: &str) {
println!("{}", r.reply(msg));
}
 
fn main() {
talk(&Mute, "hello");
}

What happens when this program is compiled?

  • It compiles and runs
  • Compile error E0277
  • It compiles, then panics
Reveal the answer

It does not compile: E0277. E0277 is "the trait bound is not satisfied". Mute never wrote impl Replier for Mute, so it cannot be used where a Replier is expected. This is checked before the program ever runs.

error[E0277]: the trait bound `Mute: Replier` is not satisfied
  --> src/main.rs:12:10
   |
12 |     talk(&Mute, "hello");
   |          ^^^^^ unsatisfied trait bound
   |
help: the trait `Replier` is not implemented for `Mute`
  --> src/main.rs:5:1
   |
 5 | struct Mute;
   | ^^^^^^^^^^^
help: this trait has no implementations, consider adding one
  --> src/main.rs:1:1
   |
 1 | trait Replier {
   | ^^^^^^^^^^^^^
   = note: required for the cast from `&Mute` to `&dyn Replier`

Fixed while compiling, or chosen while running

Chatterbox has to choose who answers while it runs, because you can type /model pretend in the middle of a chat. A generic cannot do that. For ask<T>, the compiler writes a separate copy of the function for each type it is called with, and at every call the type is already decided. And a plain variable cannot change kind: once it holds an Echo, its type is Echo forever.

Compiler CoachThe compiler, translated

This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.

trait Replier {
fn name(&self) -> &str;
}
 
struct Echo;
struct Pretend;
 
impl Replier for Echo {
fn name(&self) -> &str {
"echo"
}
}
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
}
 
fn main() {
let mut replier = Echo;
println!("{}", replier.name());
replier = Pretend;
println!("{}", replier.name());
}
error[E0308]: mismatched types
  --> src/main.rs:23:15
   |
21 |     let mut replier = Echo;
   |                       ---- expected due to this value
22 |     println!("{}", replier.name());
23 |     replier = Pretend;
   |               ^^^^^^^ expected `Echo`, found `Pretend`

E0308 in the compiler error atlas →

  1. mismatched types: the variable is an Echo, and you tried to put a Pretend in it.
  2. expected `Echo`, found `Pretend`: let mut replier = Echo; fixed the type on that first line. mut lets the value change, never the type.
  3. Both types implement Replier, and the compiler still says no: to the compiler a promise two types share does not make them the same type.

Fixes that were compiled for real

  • Put it in a Box<dyn Replier> — compiles. The variable now holds a box that points at some Replier on the heap. Swapping puts a new box in, and the old one is dropped. This is what Chatterbox does.
  • Borrow it as &dyn Replier — compiles. Also works when both values live somewhere else for long enough. Chatterbox builds its repliers on the spot inside /model, so it needs a Box that owns the value.
  • Trap: box it without dyn — still E0308. <code>Box&lt;Echo&gt;</code> is a box that can only ever hold an Echo. The <code>dyn Replier</code> part is what says "any Replier".

A Box is a pointer (a small value that says where another value lives) to a value it owns on the heap (lesson 4.1). dyn means "some type that implements this trait, decided while the program runs". Echo and Pretend can be different sizes, and a variable needs one size, but the box is always the same size whatever is inside it: so Box<dyn Replier> can hold either, and the next one too.

How does replier.name() know whose name to run? A pointer to a dyn value is two pointers: one to the value, and one to a small table of that type's methods, called a vtable. Each call looks up the method in the table first. That lookup is the small price of choosing at run time; a generic pays nothing at run time, because each copy calls its type's method directly. Try both below.

DispatchT: Replier or dyn Replier

Switch between the two tabs and make a call with each kind of replier.

With a generic, ask::<Echo> and ask::<Pretend> are two separate copies of the function in the finished program, and each call jumps straight to the right one. With dyn Replier there is one function; the pointer it is given carries a second pointer to the vtable for Echo or for Pretend, and each call looks the method up there.

Chatterbox gets repliers

All of this lives in a new module, replier.rs. Two types keep the promise:

  • Echo is the old reply function moved into a type. The length limit it read from the constant MAX_LEN is now its one field, max_len, filled in from MAX_LEN when an Echo is made. Its reply takes the last message with history.last(), which gives an Option (lesson 5.4) because a history can be empty, and answers exactly as before.
  • Pretend is a stand-in for a real model. It has no fields at all (pub struct Pretend;), and its answer proves it was handed the whole conversation: it says how many messages it read.

Here is what changed in main.rs, all green below:

  • let mut replier: Box<dyn Replier> = Box::new(Echo { max_len: MAX_LEN }); starts with the echo. The banner now says who replies, Chatterbox v0.8 (replies by: echo), and the old reply function is gone from main.rs. Its two tests are not thrown away: they moved with it into replier.rs, as echo_repeats_you and echo_refuses_long_messages, next to a new one for Pretend. The safety net from lesson 7.3 comes along with the code it guards.
  • For a chat line, your message goes into the history first, then replier.reply(&history) is asked for an answer, which is printed and pushed too. The loop never knows which kind of replier it is talking to.
  • /again asks with a one-message slice made on the spot, &[Message::new("you", text)].
  • use replier::{Echo, Pretend, Replier}; brings the trait in as well as the two types. Rust only lets you call a trait's methods where the trait's name is in scope.

command.rs gets a Model(String) variant, built with need like /say, and HELP lists /model <echo|pretend>. In main, the Model arm matches on choice.as_str(), which borrows the String as a &str so it can be compared with text in quotes. It builds an Option<Box<dyn Replier>>: a new box for a name it knows, None for anything else. With Some(r), replier = r; swaps the box. The old box loses its owner and is dropped right there (chapter 4's one-owner rule doing the tidying). The history on disk does not change: store.rs still writes one author: text line per message, as in lesson 8.2.

Chatterbox v0.8 after lesson 8.4: the whole program (green lines are new in this lesson)
You type
Sam
hi
/model pretend
still there
/model banana
/model echo
back
/quit
Chatterbox prints (a real run)
Chatterbox v0.8 (replies by: echo)
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hi
bot: replies now come from pretend
bot: (pretend model) I read all 3 messages. You last said: still there
bot: I don't know a model called banana. Try echo or pretend
bot: replies now come from echo
bot: you said: back
bot: bye, Sam!
messages so far: 3
saved 6 messages to chatterbox.log
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs31 new lines
// Chatterbox: a small chat program, built one lesson at a time.
mod command;
mod message;
mod replier;
mod store;
 
use command::{Command, parse};
use message::Message;
use replier::{Echo, Pretend, Replier};
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>, /model <echo|pretend>, /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
}
 
/// The last `n` items of any slice: messages, numbers, words, anything.
/// `<T>` says "for any type T"; the body never needs to know which one.
fn last_n<T>(items: &[T], n: usize) -> &[T] {
let start = items.len().saturating_sub(n);
&items[start..]
}
 
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
// Box<dyn Replier>: "some Replier, decided while the program runs".
let mut replier: Box<dyn Replier> = Box::new(Echo { max_len: MAX_LEN });
 
println!("{} (replies by: {})", banner(), replier.name());
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 => match &last {
Some(text) => println!("bot: {}", replier.reply(&[Message::new("you", text)])),
None => 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) => {
for m in last_n(&history, n) {
println!("{}", m.to_line());
}
}
Command::Model(choice) => {
let next: Option<Box<dyn Replier>> = match choice.as_str() {
"echo" => Some(Box::new(Echo { max_len: MAX_LEN })),
"pretend" => Some(Box::new(Pretend)),
_ => None,
};
match next {
Some(r) => {
replier = r;
println!("bot: replies now come from {}", replier.name());
}
None => {
println!("bot: I don't know a model called {choice}. Try echo or pretend")
}
}
}
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;
history.push(Message::new("you", &text));
// the history holds its own copy, so `text` can move into `last`
last = Some(text);
let answer = replier.reply(&history);
println!("bot: {answer}");
history.push(Message::new("bot", &answer));
}
}
}
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 last_n_takes_from_the_end() {
assert_eq!(last_n(&[1, 2, 3, 4], 2), &[3, 4]);
assert_eq!(last_n(&["a", "b"], 5), &["a", "b"]);
assert!(last_n(&[1, 2, 3], 0).is_empty());
}
}
src/command.rs2 new lines
//! 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),
Model(String),
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")?)?),
"/model" => Command::Model(need(line, "model", "pretend")?),
"/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/replier.rsnew file
//! Who answers: anything that can reply, behind one trait.
use crate::message::Message;
 
/// A promise with a name: any type that implements Replier can answer a
/// conversation. The chat loop only ever talks to this promise.
pub trait Replier {
/// A short name, for "/model" and the banner.
fn name(&self) -> &str;
/// The answer to the conversation so far (the last message is the newest).
fn reply(&self, history: &[Message]) -> String;
}
 
/// The echo Chatterbox has had since chapter 3, now as one kind of Replier.
pub struct Echo {
pub max_len: usize,
}
 
impl Replier for Echo {
fn name(&self) -> &str {
"echo"
}
 
fn reply(&self, history: &[Message]) -> String {
let message = match history.last() {
Some(m) => &m.text,
None => return String::from("(nothing to reply to)"),
};
if message.len() > self.max_len {
format!("that is too long (the limit is {} bytes)", self.max_len)
} 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}")
}
}
}
 
/// A stand-in for a real model: it shows that it was handed the WHOLE
/// conversation, which is exactly what the real one will need.
pub struct Pretend;
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
 
fn reply(&self, history: &[Message]) -> String {
match history.last() {
Some(m) => format!(
"(pretend model) I read all {} message{}. You last said: {}",
history.len(),
if history.len() == 1 { "" } else { "s" },
m.text
),
None => String::from("(pretend model) nothing to read yet"),
}
}
}
 
#[cfg(test)]
mod tests {
use super::*;
 
fn said(text: &str) -> Vec<Message> {
vec![Message::new("you", text)]
}
 
#[test]
fn echo_repeats_you() {
assert_eq!(Echo { max_len: 200 }.reply(&said("hi")), "you said: hi");
}
 
#[test]
fn echo_refuses_long_messages() {
assert!(
Echo { max_len: 5 }
.reply(&said("far too long"))
.starts_with("that is too long")
);
}
 
#[test]
fn pretend_reads_the_whole_history() {
let history = vec![
Message::new("you", "a"),
Message::new("bot", "b"),
Message::new("you", "c"),
];
assert_eq!(
Pretend.reply(&history),
"(pretend model) I read all 3 messages. You last said: c"
);
}
}
src/store.rsunchanged
//! 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))
}

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

Read the run. The first answer is the echo. After /model pretend, the next answer says it read all 3 messages: your hi, the echo's answer, and still there. That is the whole history arriving through &history. /model banana is a name nobody knows, so nothing changes. /model echo swaps back. The chat loop did not change once.

Try itYour turn: the Pretend replier in Chatterbox

This is the whole Chatterbox program with the body of Pretend's reply taken out. Put it back. For a history ending in c with 3 messages it answers (pretend model) I read all 3 messages. You last said: c; with exactly one message it says 1 message, not 1 messages; and for an empty history (pretend model) nothing to read yet.

This is the whole Chatterbox program with the body of Pretend's reply taken out. Put it back. For a history ending in c with 3 messages it answers (pretend model) I read all 3 messages. You last said: c; with exactly one message it says 1 message, not 1 messages; and for an empty history (pretend model) nothing to read yet.

// Chatterbox: a small chat program, built one lesson at a time.
mod command {
//! 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),
Model(String),
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")?)?),
"/model" => Command::Model(need(line, "model", "pretend")?),
"/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());
}
}
}
mod message {
//! 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()
}
}
}
mod replier {
//! Who answers: anything that can reply, behind one trait.
use crate::message::Message;
 
/// A promise with a name: any type that implements Replier can answer a
/// conversation. The chat loop only ever talks to this promise.
pub trait Replier {
/// A short name, for "/model" and the banner.
fn name(&self) -> &str;
/// The answer to the conversation so far (the last message is the newest).
fn reply(&self, history: &[Message]) -> String;
}
 
/// The echo Chatterbox has had since chapter 3, now as one kind of Replier.
pub struct Echo {
pub max_len: usize,
}
 
impl Replier for Echo {
fn name(&self) -> &str {
"echo"
}
 
fn reply(&self, history: &[Message]) -> String {
let message = match history.last() {
Some(m) => &m.text,
None => return String::from("(nothing to reply to)"),
};
if message.len() > self.max_len {
format!("that is too long (the limit is {} bytes)", self.max_len)
} 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}")
}
}
}
 
/// A stand-in for a real model: it shows that it was handed the WHOLE
/// conversation, which is exactly what the real one will need.
pub struct Pretend;
 
impl Replier for Pretend {
fn name(&self) -> &str {
"pretend"
}
 
fn reply(&self, history: &[Message]) -> String {
todo!()
}
}
 
#[cfg(test)]
mod tests {
use super::*;
 
fn said(text: &str) -> Vec<Message> {
vec![Message::new("you", text)]
}
 
#[test]
fn echo_repeats_you() {
assert_eq!(Echo { max_len: 200 }.reply(&said("hi")), "you said: hi");
}
 
#[test]
fn echo_refuses_long_messages() {
assert!(
Echo { max_len: 5 }
.reply(&said("far too long"))
.starts_with("that is too long")
);
}
 
#[test]
fn pretend_reads_the_whole_history() {
let history = vec![
Message::new("you", "a"),
Message::new("bot", "b"),
Message::new("you", "c"),
];
assert_eq!(
Pretend.reply(&history),
"(pretend model) I read all 3 messages. You last said: c"
);
}
}
}
mod store {
//! 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))
}
}
use command::{Command, parse};
use message::Message;
use replier::{Echo, Pretend, Replier};
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>, /model <echo|pretend>, /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
}
 
/// The last `n` items of any slice: messages, numbers, words, anything.
/// `<T>` says "for any type T"; the body never needs to know which one.
fn last_n<T>(items: &[T], n: usize) -> &[T] {
let start = items.len().saturating_sub(n);
&items[start..]
}
 
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
// Box<dyn Replier>: "some Replier, decided while the program runs".
let mut replier: Box<dyn Replier> = Box::new(Echo { max_len: MAX_LEN });
 
println!("{} (replies by: {})", banner(), replier.name());
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 => match &last {
Some(text) => println!("bot: {}", replier.reply(&[Message::new("you", text)])),
None => 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) => {
for m in last_n(&history, n) {
println!("{}", m.to_line());
}
}
Command::Model(choice) => {
let next: Option<Box<dyn Replier>> = match choice.as_str() {
"echo" => Some(Box::new(Echo { max_len: MAX_LEN })),
"pretend" => Some(Box::new(Pretend)),
_ => None,
};
match next {
Some(r) => {
replier = r;
println!("bot: replies now come from {}", replier.name());
}
None => {
println!("bot: I don't know a model called {choice}. Try echo or pretend")
}
}
}
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;
history.push(Message::new("you", &text));
// the history holds its own copy, so `text` can move into `last`
last = Some(text);
let answer = replier.reply(&history);
println!("bot: {answer}");
history.push(Message::new("bot", &answer));
}
}
}
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 last_n_takes_from_the_end() {
assert_eq!(last_n(&[1, 2, 3, 4], 2), &[3, 4]);
assert_eq!(last_n(&["a", "b"], 5), &["a", "b"]);
assert!(last_n(&[1, 2, 3], 0).is_empty());
}
}

Hidden tests (4): an_empty_history_has_nothing_to_read one_message_is_enough pretend_reads_the_whole_history the_name_is_pretend

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

If you have coded before

In Python you would write a class with a reply method and rely on "if it quacks, it is a duck". A Protocol or abstract base class makes the promise explicit. A Rust trait is that, enforced by the compiler: calling reply on something that never made the promise does not compile. Box<dyn Replier> is closest to what every Python variable already is: a reference to some object, with the method looked up when it is called.

What you have now

Chatterbox v0.8 has a Replier trait, two types that keep it, and a /model command that swaps between them while you chat. The chat loop only ever holds a Box<dyn Replier>. The next lesson changes no code: it answers a question left open since first_word in lesson 4.6. Then, as a preview, chapter 9 adds a third replier that is not pretending: it sends the history to a real model.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is a trait?Reveal
A named list of methods a type can promise to have. Any type that writes impl Trait for Type keeps the promise.
What does <code>T: Replier</code> add to a generic function?Reveal
A trait bound: T can be any type, as long as it implements Replier, so the function is allowed to call Replier's methods on it.
What does <code>Box&lt;dyn Replier&gt;</code> mean, and why does Chatterbox need it instead of a generic?Reveal
A pointer to some value on the heap that implements Replier, with the exact type decided at run time. Chatterbox swaps repliers while it runs, and a generic fixes the type when the program is compiled.
What error appears when you pass a type that does not implement the trait?Reveal
E0277, the trait bound is not satisfied.

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

Questions people ask

What is a trait in Rust?

A set of method signatures that different types can implement. It is Rust's way of describing shared behaviour, similar to an interface in other languages.

What is the difference between generics with a trait bound and dyn Trait?

A generic with a bound, like T: Replier, is turned into one copy of the code per type when the program is compiled, so the type is fixed at each call. dyn Trait, usually behind a Box or a reference, lets the concrete type be chosen while the program runs, at the cost of looking each method up in a small table.

Why do I need Box for a trait object?

Different implementors have different sizes and a variable needs one size. A Box is a pointer, which always has the same size, to the value on the heap.

Why can I not call a trait method even though the type implements it?

The trait itself has to be in scope where you call the method. Add a use line that names the trait, as Chatterbox does with use replier::Replier.

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