Lesson 5.3 · 8 min
One of several: enum
Chatterbox decides what to do by comparing strings like "/help". A typo in one of them compiles fine and fails at run time. An enum lists every possible command once, and the compiler holds you to it.
Adds to ChatterboxA Command enum, matched exhaustively.
A value that is exactly one of these
A struct says "this and this and this". An enum says "this or that or the other". A line you type to Chatterbox is one of a few things: ask for help, quit, say something, or something it does not understand.
Each option is a variant, and a variant can carry its own data. Say carries the text to say; Unknown carries the line it could not read; Help and Quit carry nothing. We start with a small four-variant version to see how it works; Chatterbox gets the full one at the end of the lesson.
$ cargo run
hello
byeIn match (lesson 3.2) you matched text. Here each arm names a variant, written with the type in front: Command::Help is "the Help that belongs to Command", the same :: as in Message::new. And Say(text) also pulls the data out and gives it a name inside that arm. Because cmd is owned, text is moved out of it: the arm simply hands the string on.
Now delete an arm and see what the compiler thinks.
error[E0004]: non-exhaustive patterns: `Command::Unknown(_)` not covered --> src/main.rs:9:11 | 9 | match cmd { | ^^^ pattern `Command::Unknown(_)` not covered | note: `Command` defined here --> src/main.rs:1:6 | 1 | enum Command { | ^^^^^^^ ... 5 | Unknown(String), | ------- not covered = note: the matched value is of type `Command` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown | 12 ~ Command::Say(text) => text, 13 ~ Command::Unknown(_) => todo!(), |
E0004: "non-exhaustive patterns: Command::Unknown(_) not covered". The compiler lists the case you forgot. A match must cover every variant, so adding a new command later turns every match that forgot it into a compile error. That is the whole value: a string comparison can only fail at run time, an enum fails at build time.
From a line to a Command
Something has to turn the typed line into a variant. That job is called parsing (reading text and working out what it means), so the function is parse. It borrows the line as a &str and returns a brand-new Command that owns whatever it carries. Here is a small one to practise on, simpler than the one Chatterbox will get.
What does this print?
say: [hi there]unknown: [/say hi there]other
Reveal the answer
The program prints: say: [hi there] trim() removes the outer spaces first, so the line becomes /say hi there. It does not match /help or /quit, falls to other, starts with /say , and &other[5..] is everything after those five characters.
Chatterbox v0.5: every line becomes a Command
That was a small parser for practice. Here is the real one, in the whole program after this lesson (new lines in green). Chatterbox's Command has nine variants, one for every kind of line it understands: Empty, Help, Quit, Again, History, Say(String), Shout(String), Unknown(String) for a command it does not know, and Chat(String) for ordinary talk.
Its parse looks at the first word of the line (with first_word, from lesson 4.6) and picks the variant. The last arm, word => …, has no text in quotes, only a name: it matches anything the arms above did not, and calls it word inside the arm. There it decides between Unknown (the word starts with a slash) and Chat (it does not).
Now look at the loop in main. It used to match first_word(message) against pieces of text, and its last arm had to work out for itself whether a line was an unknown command or ordinary chat. Now it is one match parse(message) with an arm for each variant, and that decision lives in parse. Command::Empty => {} is an arm that does nothing at all, on purpose: a blank line gets no answer. What each command does has not changed; only how the loop finds out which command it has.
When a later lesson adds a command, as one soon will, and forgets to handle it in main, the program will not build. That is the promise you saw with E0004, now guarding the real program.
Sam /dance /quit
Chatterbox v0.5 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: I don't know the command /dance. Try /help. bot: bye, Sam! messages so far: 0
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.
This is the whole Chatterbox program with the body of parse taken out. Write it again: one arm per command word, and a last arm that tells an unknown command from ordinary chat. An empty line is Command::Empty. first_word, rest_of and is_command are there to help.
This is the whole Chatterbox program with the body of parse taken out. Write it again: one arm per command word, and a last arm that tells an unknown command from ordinary chat. An empty line is Command::Empty. first_word, rest_of and is_command are there to help.
Hidden tests (6): empty_line_is_empty plain_commands say_carries_the_text plain_text_is_chat shout_carries_the_text unknown_carries_the_word
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Say it out loud, then reveal
What can a variant like <code>Say(String)</code> do that a plain constant cannot?Reveal
What does E0004 protect you from?Reveal
Why does <code>parse</code> take <code>&str</code> but return an owned <code>Command</code>?Reveal
That is lesson 5.3. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is an enum in Rust?
An enum is a type whose value is exactly one of a fixed list of options, called variants. For example, a Command can be Help, Quit, Say or Unknown, and never anything else.
Can a Rust enum variant hold data?
Yes. A variant like Say(String) carries a String inside it, and a match arm such as Command::Say(text) pulls that data out and names it.
What is the difference between a struct and an enum?
A struct holds all of its fields at once: this and this. An enum holds exactly one of its variants at a time: this or that.
Why use an enum instead of comparing strings?
A typo in a string still compiles and only fails when the program runs. With an enum, the compiler checks every match covers every variant, so a forgotten case fails before the program runs.