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>.
$ 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.
What does this print?
truefalse-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.
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.
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.
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
Commandenum gets a new variant,Last(Option<String>). It holds the text after/last, orNonewhen you typed/laston its own, exactly likeFinddid in lesson 6.4.parsegets one new line that builds it, andHELPlists/last <n>. - A new function,
parse_count, does the risky part: it turns that text into a number. Its return type isResult<usize, ParseIntError>.usizeis 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 withhistory.len().ParseIntErroris the standard library's reason for "that text is not a whole number", and theuseline at the top brings its name in. - In
main, amatchon 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.
Sam first second /last 2 /last two /last /last 99 /quit
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)
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.
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.
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.
Say it out loud, then reveal
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
Does Rust throw exceptions?Reveal
That is lesson 7.1. Tick it off so the course remembers where you are.
Go deeper
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.
