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.1 · 8 min

Operations that can fail: Result

Someone types "/last two" instead of "/last 2". Chatterbox cannot turn "two" into a number, and it must say so instead of crashing. Rust makes "this might fail" part of the answer itself.

Adds to Chatterbox/last N: turning text into a number can fail.

An answer or a reason

Chatterbox is about to get a /last 3 command: show the last three messages. The "3" arrives as text, so the program has to turn text into a number. That can fail, because the person might type /last two or /last -1 or /last and nothing else.

Some languages handle this by throwing an exception that flies up the program until something catches it. Rust has no exceptions. Instead, a function that can fail returns a value of a type called Result. It is an enum (lesson 5.3) with exactly two variants:

  • Ok(value): it worked, and here is the value.
  • Err(reason): it did not work, and here is why.

The type is written Result<T, E>: T is the kind of value you get on success, E is the kind of reason you get on failure. Turning text into a u32 returns Result<u32, ParseIntError>.

parse gives back a Result, not a number
fn main() {
let good = "3".parse::<u32>();
let bad = "three".parse::<u32>();
println!("{:?}", good);
println!("{:?}", bad);
}
$ cargo run
Ok(3)
Err(ParseIntError { kind: InvalidDigit })

{:?} is the debug form from lesson 5.5, the one Chatterbox's /debug uses: it shows the variant name, so you see Ok(3) or Err(...) rather than just a number. Standard library types such as Result already know how to print themselves this way, with no #[derive(Debug)] from you.

PredictWhich one is it?
fn main() {
let r = "-1".parse::<u32>();
println!("{}", r.is_ok());
}

What does this print?

  • true
  • false
  • -1
Reveal the answer

The program prints: false A u32 cannot be negative, so "-1" is not a valid u32 and you get an Err. is_ok() asks "is it the Ok variant?" and the answer is no.

You cannot ignore it

Here is the part that makes Rust different. A Result is not a number. You cannot add to it or print it as a count. To get at the value inside you must say what to do in both cases, and the tool for that is match from lesson 3.2. Try to cover only the happy case and the compiler stops you.

Only handling Ok
fn main() {
let r = "3".parse::<u32>();
match r {
Ok(n) => println!("count is {n}"),
}
}
error[E0004]: non-exhaustive patterns: `Err(_)` not covered
 --> src/main.rs:3:11
  |
3 |     match r {
  |           ^ pattern `Err(_)` not covered
  |
note: `Result<u32, ParseIntError>` defined here
 --> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/result.rs:558:0
 ::: /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/result.rs:567:4
  |
  = note: not covered
  = note: the matched value is of type `Result<u32, ParseIntError>`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
4 ~         Ok(n) => println!("count is {n}"),
5 ~         Err(_) => todo!(),
  |

The message says a pattern is not covered: Err(_). That is the whole safety idea. A failure that nobody wrote code for is a compile error, not a surprise at 2 a.m.

If you have coded before

In Python, int("two") raises ValueError and you only find out if you remember a try/except. In Rust the possibility of failure is in the function's return type, so you see it before you call it and the compiler checks that you dealt with it.

Try itWarm-up: a count that never crashes

A small separate example before we touch Chatterbox. Write count_or_default. It parses arg as a u32 and returns it. If parsing fails it returns default instead. Use match on the Result.

A small separate example before we touch Chatterbox. Write count_or_default. It parses arg as a u32 and returns it. If parsing fails it returns default instead. Use match on the Result.

fn count_or_default(arg: &str, default: u32) -> u32 {
// parse arg, then match on Ok and Err
0
}
 
fn main() {
println!("{}", count_or_default("3", 5));
println!("{}", count_or_default("three", 5));
}

Hidden tests (4): good_number bad_text_uses_default negative_uses_default spaces_are_fine

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

Chatterbox gets /last

Now the real thing. /last 3 prints the last three lines of the history (your messages and the bot's answers, in order), so you can look back without scrolling through everything that /history prints. Here is what changed in the program, in green:

  • The Command enum gets a new variant, Last(Option<String>). It holds the text after /last, or None when you typed /last on its own, exactly like Find did in lesson 6.4. parse gets one new line that builds it, and HELP lists /last <n>.
  • A new function, parse_count, does the risky part: it turns that text into a number. Its return type is Result<usize, ParseIntError>. usize is the number type Rust uses for lengths and positions in a list (it can never be negative), so the count can be compared straight away with history.len(). ParseIntError is the standard library's reason for "that text is not a whole number", and the use line at the top brings its name in.
  • In main, a match on that Result handles both outcomes. Ok(n) works out where to start and prints from there to the end. Err(e) prints the text back with the reason the standard library gave, then the loop simply carries on to your next line. Nothing crashes.

One line needs a closer look: let start = if n >= history.len() { 0 } else { history.len() - n };. If you ask for 99 messages and there are only 4, subtracting would go below zero, and a usize cannot be negative: the program would stop with an error. So when you ask for more than there is, we start at 0 and show everything. &history[start..] is a slice (lesson 4.6): a borrowed view of the history from position start to the end.

Chatterbox v0.7 after lesson 7.1: 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 (invalid digit found in string)
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.rs25 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::io;
use std::num::ParseIntError;
 
/// 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>),
Usage(String),
Find(Option<String>),
Last(Option<String>),
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// How many messages /last should show. Turning text into a number can
/// fail ("two", "-1"), so the answer is a Result: Ok(number) or Err(why).
fn parse_count(text: &str) -> Result<usize, ParseIntError> {
text.parse::<usize>()
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
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" => match arg(line) {
Some(rest) => match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => Command::Usage(String::from("/remember <name> <fact>")),
},
None => Command::Usage(String::from("/remember <name> <fact>")),
},
"/recall" => Command::Recall(owned(arg(line))),
"/find" => Command::Find(owned(arg(line))),
"/last" => Command::Last(owned(arg(line))),
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// 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();
match parse(message) {
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(Some(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::Find(None) => println!("bot: find what? Try /find hello"),
Command::Last(Some(text)) => match parse_count(&text) {
Ok(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());
}
}
Err(e) => println!("bot: '{}' is not a count ({})", text, e),
},
Command::Last(None) => println!("bot: last what? Try /last 3"),
Command::Usage(form) => println!("bot: try {}", form),
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
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);
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "0.7.0"
edition = "2024"
 
[dependencies]

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

Read the run from top to bottom. /last 2 shows your second message and its answer. /last two is an Err, so Chatterbox says what went wrong and keeps listening. A bare /last never reaches parse_count at all: it is Last(None), and the answer is a hint. /last 99 asks for more than there is and gets the whole history.

Try itYour turn: parse_count in Chatterbox

This is the whole Chatterbox program with the body of parse_count taken out. Put it back: turn text into a usize and return the Result as it is, so that "3" gives Ok(3) and "two", "-1" and "" all give an Err.

This is the whole Chatterbox program with the body of parse_count taken out. Put it back: turn text into a usize and return the Result as it is, so that "3" gives Ok(3) and "two", "-1" and "" all give an Err.

// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::io;
use std::num::ParseIntError;
 
/// 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>),
Usage(String),
Find(Option<String>),
Last(Option<String>),
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// How many messages /last should show. Turning text into a number can
/// fail ("two", "-1"), so the answer is a Result: Ok(number) or Err(why).
fn parse_count(text: &str) -> Result<usize, ParseIntError> {
todo!()
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
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" => match arg(line) {
Some(rest) => match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => Command::Usage(String::from("/remember <name> <fact>")),
},
None => Command::Usage(String::from("/remember <name> <fact>")),
},
"/recall" => Command::Recall(owned(arg(line))),
"/find" => Command::Find(owned(arg(line))),
"/last" => Command::Last(owned(arg(line))),
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// 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();
match parse(message) {
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(Some(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::Find(None) => println!("bot: find what? Try /find hello"),
Command::Last(Some(text)) => match parse_count(&text) {
Ok(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());
}
}
Err(e) => println!("bot: '{}' is not a count ({})", text, e),
},
Command::Last(None) => println!("bot: last what? Try /last 3"),
Command::Usage(form) => println!("bot: try {}", form),
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
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 (4): a_negative_number_is_an_error a_number_is_ok a_word_is_an_error empty_text_is_an_error

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

What you have now

Chatterbox can read a count from the user and survive a bad one. The failure is a value you can match on, print, or turn into a friendlier message. Coming up, as a preview: the very next lesson shows how to pass a failure up to the caller in a single character, so you do not write a match at every step.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What are the two variants of Result<T, E>?Reveal
Ok(T) for success carrying the value, and Err(E) for failure carrying the reason.
Why does Rust refuse a match that only covers Ok?Reveal
Because the Err case would be silently unhandled. A failure nobody wrote code for becomes a compile error.
Does Rust throw exceptions?Reveal
No. A function that can fail returns a Result and the caller decides what to do.

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

Next: 7.2 The ? operator →

Questions people ask

What is Result in Rust?

Result is the type a function returns when it might fail. It is either Ok(value) when it worked or Err(reason) when it did not, and the caller has to handle both.

How do I convert a string to a number in Rust?

Call parse on the text and tell it which number type you want, such as u32. It returns a Result, because the text might not be a valid number.

How do I print a Result to see what is inside?

Use {:?} in println!, the debug form. It shows the variant and what it carries, such as Ok(3) or Err(ParseIntError { kind: InvalidDigit }).

What is the difference between Option and Result?

Option says a value may be missing: Some or None. Result says an operation may fail, and if it does, Err carries the reason why.

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