Vibe Engines
YouTube

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

Learn RustChapter 7: Errors and tests

Lesson 7.2 · 11 min

The ? operator

A line like "/last two" can be wrong in several ways, and right now every "what?" answer is scattered through the chat loop. Better: the function that reads the line says what is wrong, and hands that answer up to whoever asked. One character makes that short.

Adds to Chatterboxparse() reports what is wrong, passed up with ?.

Passing the problem upward

In lesson 7.1 every Result was handled right where it appeared, with a match. Often a function can do nothing useful with a failure except hand it to whoever called it. Rust gives that one character: ?. Here it is in a tiny program, before we touch Chatterbox.

Three lines of match become one character
use std::num::ParseIntError;
 
fn double(arg: &str) -> Result<u32, ParseIntError> {
let n = arg.trim().parse::<u32>()?;
Ok(n * 2)
}
 
fn main() {
println!("{:?}", double("21"));
println!("{:?}", double("x"));
}
$ cargo run
Ok(42)
Err(ParseIntError { kind: InvalidDigit })

Look at the line with the ? on it. When parsing gives Ok(21), the ? takes the 21 out and n is 21. When it gives Err(...), the ? stops double right there and returns that Err to main; the Ok(n * 2) line never runs. Without ?, that one line would be a match with two arms, like the ones in lesson 7.1.

Two rules come with it. ? only works inside a function that itself returns a Result, because it needs somewhere to send the Err. And the success value is wrapped again at the end with Ok(...), since the function promised a Result. One more thing, as a preview: when the error ? meets is a different type from the one the function promises, it can convert it on the way up, through a trait called From. The JSON lesson near the end of the course leans on that.

PredictWhich message prints?
use std::num::ParseIntError;
 
fn first(a: &str, b: &str) -> Result<u32, ParseIntError> {
let x = a.parse::<u32>()?;
let y = b.parse::<u32>()?;
Ok(x + y)
}
 
fn main() {
match first("4", "oops") {
Ok(n) => println!("{n}"),
Err(_) => println!("failed"),
}
}

What does this print?

  • 4
  • failed
  • 0
Reveal the answer

The program prints: failed The first ? succeeds and gives 4. The second sees an Err and returns it from first at once, so the sum never happens and main takes the Err arm.

Step 1: a name for each problem

Chatterbox has a whole family of "that line is not right" answers, and they live in different places: parse builds Usage and Unknown commands, and main prints "say what?", "shout what?", "find what?", "debug what?" and "last what?" in five separate arms. None of those are really commands. They are reasons a line could not become one. So they get their own enum:

One variant per kind of problem
#[derive(Debug)]
enum CommandError {
Unknown(String), // a command nobody has heard of: /dance
Missing(String, String), // a bare /say: the verb, and an example to suggest
Usage(String), // the wrong shape: /remember pizza, with no fact
NotACount(String), // /last two
}
 
fn main() {
let problem = CommandError::Missing(String::from("say"), String::from("hello"));
println!("{:?}", problem);
}
$ cargo run
Missing("say", "hello")

Step 2: one helper, with a ? after it

A bare /say, /shout, /find, /debug or /last is the same mistake five times. So one small function, need, gets the text after the command word, or gives back a Missing error. Here it is with a tiny caller, so you can watch the ? work:

need gives the text or the reason; ? passes the reason up
#[derive(Debug)]
enum CommandError {
Missing(String, String),
}
 
/// The text after the command word, if there is any (lesson 5.4).
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,
}
}
 
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))),
}
}
 
fn say(line: &str) -> Result<String, CommandError> {
let text = need(line, "say", "hello")?;
Ok(format!("bot: {}", text))
}
 
fn main() {
println!("{:?}", say("/say hi"));
println!("{:?}", say("/say"));
}
$ cargo run
Ok("bot: hi")
Err(Missing("say", "hello"))

That is exactly what Chatterbox's parse does now, five times. It promises Result<Command, CommandError>: either a command, or the reason there is none. A line such as "/say" => Command::Say(need(line, "say", "hello")?), reads: get the text, and if that failed, return its error from parse right now. Where there is no helper to put a ? after, as in the /remember arm and the unknown-command arm, return Err(...) does the same job by hand. Every arm that gets to the end has made a plain Command, so the last line of parse wraps it: Ok(cmd).

Because "nothing after it" is now an error rather than a command, Say, Shout, Find and Debug hold a plain String instead of an Option, and Last holds a ready-made number.

Going deeper The rest of the changes inside parse

Two ? marks in a row. The /last line is parse_count(&need(line, "last", "3")?)?. Read it from the inside out: first the text must be there (the inner ?), then it must be a number (the outer one). Either can stop parse early. For that to work, parse_count now turns the standard library's ParseIntError into our own NotACount with a match, so every failure inside parse has the same type.

Recall keeps its Option. A bare /recall is not a mistake: it lists everything Chatterbox remembers. So Recall still holds an Option.

The owned helper is gone. It turned a borrowed Option into an owned one for the variants that held an Option. They hold a plain String now, which need makes, so nothing needs it any more.

A short detour: teaching an error to speak

Chatterbox wants to print a CommandError as a sentence, with {}, not in the debug form. This section is mostly a shape to copy. Here it is on its own:

Display: the sentence a value reads as when printed with {}
use std::fmt;
 
enum CommandError {
Missing(String, String),
NotACount(String),
}
 
impl fmt::Display for CommandError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CommandError::Missing(verb, example) => {
write!(f, "{} what? Try /{} {}", verb, verb, example)
}
CommandError::NotACount(text) => write!(f, "'{}' is not a count. Try /last 3", text),
}
}
}
 
fn main() {
println!("bot: {}", CommandError::Missing(String::from("say"), String::from("hello")));
println!("bot: {}", CommandError::NotACount(String::from("two")));
}
$ cargo run
bot: say what? Try /say hello
bot: 'two' is not a count. Try /last 3
  • impl fmt::Display for CommandError is a promise: this type can be printed with {}. Display is a trait, a named promise that a type can do something. Traits get their own lesson, 8.4, as a preview; for now copy the shape and change only the sentences. use std::fmt; at the top brings in the name fmt, and fmt::Display is the Display that belongs to fmt.
  • fn fmt(&self, f: &mut fmt::Formatter) is the one method the promise asks for. &self is the error being printed (methods, lesson 5.2). f, the formatter, is where the text goes; println! hands it in. It is &mut because writing into it changes it (lesson 4.5).
  • write! works like println!, but sends the text into f instead of to the screen. A match on self picks the sentence for each variant.
  • fmt::Result has no <T, E> after it, unlike the Result of lesson 7.1. It is a short name the fmt part of the standard library gives to Result<(), fmt::Error>. Success carries (), nothing (lesson 1.6), because the text has already gone into f. Each write! gives back exactly that kind of value, which is why each arm can end with one.

Step 3: one place that prints problems

In main, the chat loop now opens with a match on what parse returned. Ok(cmd) hands the command on. Err(e) prints bot: and the error's sentence, then says continue. continue skips the rest of this turn of the loop and goes straight back to the top for the next line, so a broken line never reaches the big match below. Every problem Chatterbox can report now comes from one Display block and is printed by one line.

One small thing you will notice: /debug prints parse's answer with {:?}, and that answer is a Result now, so /debug /say hi shows Ok(Say("hi")) and /debug /say shows Err(Missing("say", "hello")).

Here is the whole program, with the changes in green:

Chatterbox v0.7 after lesson 7.2: the whole program (green lines are new in this lesson)
You type
Sam
first
second
/last 2
/last two
/last
/last 99
/quit
Chatterbox prints (a real run)
Chatterbox v0.7
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: first
bot: you said: second
you: second
bot: you said: second
bot: 'two' is not a count. Try /last 3
bot: last what? Try /last 3
you: first
bot: you said: first
you: second
bot: you said: second
bot: bye, Sam!
messages so far: 2
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs91 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::fmt;
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, 7);
/// 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)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// 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)]
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)]
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 {}. Try /help.", word)
}
CommandError::Missing(verb, example) => {
write!(f, "{} what? Try /{} {}", verb, verb, example)
}
CommandError::Usage(form) => write!(f, "try {}", form),
CommandError::NotACount(text) => write!(f, "'{}' is not a count. Try /last 3", text),
}
}
}
 
/// 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.
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)
}
 
/// 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 {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// 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,
}
}
 
/// 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 {} bytes)", 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)
}
}
 
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: {} is {}", key, fact);
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {} is {}", key, 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);
}

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

The run looks almost the same as in lesson 7.1, which is the point: the program behaves the same, but the decisions moved to one place. Look closely at /last two. Its answer is now the NotACount sentence, and a bare /last gets the Missing sentence, both written in the Display block.

Going deeper main can return a Result too

Because main is a function, it may return Result<(), SomeError>. Then ? works inside it, and if an Err reaches the top the program exits with an error message. Chatterbox does not need that yet. You will use it in chapter 8, as a preview, when the program starts saving the conversation to a file.

Try itYour turn: need in Chatterbox

This is the whole Chatterbox program with the body of need taken out. Put it back: return the text after the command word, or a Missing error carrying the verb and the example, in that order. The tests check the sentences Chatterbox prints, such as say what? Try /say hello.

This is the whole Chatterbox program with the body of need taken out. Put it back: return the text after the command word, or a Missing error carrying the verb and the example, in that order. The tests check the sentences Chatterbox prints, such as say what? Try /say hello.

// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::fmt;
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, 7);
/// 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)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// 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)]
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)]
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 {}. Try /help.", word)
}
CommandError::Missing(verb, example) => {
write!(f, "{} what? Try /{} {}", verb, verb, example)
}
CommandError::Usage(form) => write!(f, "try {}", form),
CommandError::NotACount(text) => write!(f, "'{}' is not a count. Try /last 3", text),
}
}
}
 
/// 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> {
todo!()
}
 
/// 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.
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)
}
 
/// 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 {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// 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,
}
}
 
/// 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 {} bytes)", 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)
}
}
 
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: {} is {}", key, fact);
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {} is {}", key, 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);
}

Hidden tests (5): need_gives_the_text the_verb_comes_first_then_the_example only_spaces_is_still_missing a_bare_last_is_missing_before_it_is_counted a_bare_command_is_missing_its_text

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

What you have now

Chatterbox names what went wrong in a sentence, and every sentence lives in one place. Errors travel up out of parse with ? and are printed once, at the top of the loop. Those sentences are now worth protecting: change one by accident and nobody would notice for weeks. As a preview, the next lesson writes Chatterbox's first tests, which check them for you.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What does ? do on an Err?Reveal
It returns that Err from the current function immediately. On an Ok it unwraps the value and continues.
Where can you use ?Reveal
Only inside a function that returns a Result (or Option), because it needs somewhere to send the failure.
Why make an enum for errors?Reveal
One variant per kind of failure lets the caller match on the cause and lets Display say it in a sentence.
What is <code>fmt::Result</code>?Reveal
A short name for Result<(), fmt::Error>: success carries nothing, because the text has already been written into the formatter.

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

Next: 7.3 Writing tests →

Questions people ask

What does the question mark operator do in Rust?

Placed after a Result, ? gives you the value inside an Ok and carries on. If it is an Err, the function stops and returns that Err to its caller.

Why does ? give an error in my main function?

The ? operator only works inside a function that returns a Result or an Option. Make main return a Result, or handle the error with match instead.

What does continue do in a Rust loop?

continue skips the rest of the current turn of the loop and starts the next one straight away. Chatterbox uses it to print an error and go back to reading the next line.

How do I make my own error type in Rust?

Write an enum with one variant per kind of failure, then implement Display for it so it can be printed as a sentence a person can read.

Why does fmt::Result have no type parameters?

It is a type alias: a short name the fmt module gives to Result with () for success and fmt::Error for failure, so you never have to spell those out.

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