Vibe Engines
YouTube

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

Learn RustChapter 5: Shapes

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.

One enum, four variants, one match
enum Command {
Help,
Quit,
Say(String),
Unknown(String),
}
 
fn handle(cmd: Command) -> String {
match cmd {
Command::Help => String::from("commands: /help /quit /say <text>"),
Command::Quit => String::from("bye"),
Command::Say(text) => text,
Command::Unknown(line) => format!("unknown: {line}"),
}
}
 
fn main() {
println!("{}", handle(Command::Say(String::from("hello"))));
println!("{}", handle(Command::Quit));
}
$ cargo run
hello
bye

In 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.

A variant nobody handled
enum Command {
Help,
Quit,
Say(String),
Unknown(String),
}
 
fn handle(cmd: Command) -> String {
match cmd {
Command::Help => String::from("help"),
Command::Quit => String::from("bye"),
Command::Say(text) => text,
}
}
 
fn main() {
println!("{}", handle(Command::Quit));
}
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.

PredictParse a line
enum Command {
Help,
Quit,
Say(String),
Unknown(String),
}
 
fn parse(line: &str) -> Command {
match line.trim() {
"/help" => Command::Help,
"/quit" => Command::Quit,
other => {
if other.starts_with("/say ") {
Command::Say(String::from(&other[5..]))
} else {
Command::Unknown(String::from(other))
}
}
}
}
 
fn main() {
match parse(" /say hi there ") {
Command::Say(t) => println!("say: [{t}]"),
Command::Unknown(l) => println!("unknown: [{l}]"),
_ => println!("other"),
}
}

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.

Chatterbox v0.5 after lesson 5.3: the whole program (green lines are new in this lesson)
You type
Sam
/dance
/quit
Chatterbox prints (a real run)
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)
src/main.rs53 new lines
// Chatterbox: a small chat program, built one lesson at a time.
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, 5);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /say <text>, /shout <text>, /quit";
 
/// 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()
}
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
log.push_str(&msg.to_line());
log.push('\n');
}
 
/// 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.
enum Command {
Empty,
Help,
Quit,
Again,
History,
Say(String),
Shout(String),
Unknown(String),
Chat(String),
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
match first_word(line) {
"" => Command::Empty,
"/help" => Command::Help,
"/quit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/say" => Command::Say(String::from(rest_of(line))),
"/shout" => Command::Shout(String::from(rest_of(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,
}
}
 
/// Everything after the first space, or "" when there is no space.
fn rest_of(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[i + 1..],
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 = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
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 last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
Command::History => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
Command::Say(text) => println!("bot: {}", text),
Command::Shout(text) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
record(&mut transcript, &said);
record(&mut transcript, &answer);
println!("bot: {}", answer.text);
last = said.text; // the text moves out of `said`, which is not used again
}
}
}
println!("messages so far: {}", messages_seen);
}

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

Try itYour turn: write parse for Chatterbox

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.

// Chatterbox: a small chat program, built one lesson at a time.
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, 5);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /say <text>, /shout <text>, /quit";
 
/// 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()
}
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
log.push_str(&msg.to_line());
log.push('\n');
}
 
/// 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.
enum Command {
Empty,
Help,
Quit,
Again,
History,
Say(String),
Shout(String),
Unknown(String),
Chat(String),
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
// match on the first word, one arm per command
todo!()
}
 
/// 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,
}
}
 
/// Everything after the first space, or "" when there is no space.
fn rest_of(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[i + 1..],
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 = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
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 last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
Command::History => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
Command::Say(text) => println!("bot: {}", text),
Command::Shout(text) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
record(&mut transcript, &said);
record(&mut transcript, &answer);
println!("bot: {}", answer.text);
last = said.text; // the text moves out of `said`, which is not used again
}
}
}
println!("messages so far: {}", messages_seen);
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What can a variant like <code>Say(String)</code> do that a plain constant cannot?Reveal
Carry data with it. The text travels inside the value and you pull it out in the matching arm.
What does E0004 protect you from?Reveal
Forgetting a case. A match must cover every variant, so adding a new one turns each match that does not handle it into a compile error.
Why does <code>parse</code> take <code>&amp;str</code> but return an owned <code>Command</code>?Reveal
It only needs to read the line, so it borrows. The Command must outlive the call, so it owns its own copy of the text.

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

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.

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