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.
$ 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.
What does this print?
4failed0
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:
$ 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:
$ 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:
$ cargo run
bot: say what? Try /say hello
bot: 'two' is not a count. Try /last 3impl fmt::Display for CommandErroris a promise: this type can be printed with{}.Displayis 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 namefmt, andfmt::Displayis theDisplaythat belongs tofmt.fn fmt(&self, f: &mut fmt::Formatter)is the one method the promise asks for.&selfis the error being printed (methods, lesson 5.2).f, the formatter, is where the text goes;println!hands it in. It is&mutbecause writing into it changes it (lesson 4.5).write!works likeprintln!, but sends the text intofinstead of to the screen. Amatchonselfpicks the sentence for each variant.fmt::Resulthas no<T, E>after it, unlike theResultof lesson 7.1. It is a short name thefmtpart of the standard library gives toResult<(), fmt::Error>. Success carries(), nothing (lesson 1.6), because the text has already gone intof. Eachwrite!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:
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. 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)
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.
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.
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.
Say it out loud, then reveal
What does ? do on an Err?Reveal
Where can you use ?Reveal
Why make an enum for errors?Reveal
What is <code>fmt::Result</code>?Reveal
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.
Go deeper
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.