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.4 · 9 min

Maybe nothing: Option

What is the argument of "/help"? There is not one. Many languages answer with a special empty value called null, and you only find out it was missing when the program crashes. Rust makes "maybe nothing" a type, so you must decide up front.

Adds to ChatterboxOption: /again and a bare /say know about "nothing".

A value that may not be there

A chat command can have an argument: the hello in /say hello. But /help has none. A function that looks for the argument will sometimes come back with nothing.

Rust has no null. Instead, a value that might be missing has its own type, Option<T> (the T stands for whatever type might be inside, such as Option<&str>), which is just an enum (lesson 5.3) with two variants: Some(value) and None.

The answer is Some(rest) or None, never "empty by accident"
fn find_command_arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => Some(&line[i + 1..]),
None => None,
}
}
 
fn main() {
match find_command_arg("/say hello") {
Some(text) => println!("the argument is {text}"),
None => println!("no argument"),
}
match find_command_arg("/help") {
Some(text) => println!("the argument is {text}"),
None => println!("no argument"),
}
}
$ cargo run
the argument is hello
no argument

line.find(' ') is itself an Option: the position of the first space, or nothing. You open an Option with match, exactly like the enums in lesson 5.3. The arm Some(i) => … runs only when there is a value, and inside that arm the value has a name, i. The arm None => … runs when there is nothing. There is no third way in: no arm can reach a value that is not there.

The return type Option<&str> is a borrowed slice (lesson 4.6) that may be absent. It points into line, so nothing is copied.

You cannot use it as if it were there

Treating a maybe as a definitely
fn find_command_arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => Some(&line[i + 1..]),
None => None,
}
}
 
fn main() {
let arg: &str = find_command_arg("/help");
println!("{}", arg);
}
error[E0308]: mismatched types
 --> src/main.rs:9:21
  |
9 |     let arg: &str = find_command_arg("/help");
  |              ----   ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `Option<&str>`
  |              |
  |              expected due to this
  |
  = note: expected reference `&str`
                  found enum `Option<&str>`
help: consider using `Option::expect` to unwrap the `Option<&str>` value, panicking if the value is an `Option::None`
  |
9 |     let arg: &str = find_command_arg("/help").expect("REASON");
  |                                              +++++++++++++++++

E0308: "mismatched types: expected &str, found Option<&str>". The compiler is saying: this might be nothing, so you cannot treat it as text yet. That is the whole trick. In a language with null, this compiles and crashes when the line was /help. In Rust you cannot use a missing value by accident: the compiler makes you say what happens for None. (You can still choose to crash: .unwrap() means "give me the value, and stop the program with a panic if there is none". But that is a decision written in the code where anyone can see it, not a surprise.)

The simplest way out is unwrap_or: "give me the value, or this fallback if there is none".

PredictUse a fallback
fn find_command_arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => Some(&line[i + 1..]),
None => None,
}
}
 
fn main() {
let a = find_command_arg("/say hi");
let b = find_command_arg("/help");
println!("{} | {}", a.unwrap_or("none"), b.unwrap_or("none"));
}

What does this print?

  • hi | none
  • hi |
  • it panics
Reveal the answer

The program prints: hi | none a is Some("hi"), so unwrap_or returns hi. b is None, so it returns the fallback. The fallback is decided by you, in the code, and never skipped.

Chatterbox v0.5: knowing about nothing

Chatterbox had two places where an empty string was quietly standing in for "nothing". rest_of returned "" when there was no argument, so a bare /say made the bot print bot: and then nothing at all. And last started as an empty String meaning "you have not said anything yet". Both now say what they mean, with Option. Here is the whole program after this lesson, new lines in green.

  • arg replaces rest_of. It returns Option<&str>: Some("hello") for /say hello, and None for a bare /say or one followed only by spaces. It is find_command_arg from above, plus a trim() so that spaces alone do not count as an argument.
  • owned turns a borrowed Option<&str> into an owned Option<String>. The Command has to keep its text after the typed line is cleared for the next one, so it needs its own copy, exactly as in lesson 5.3.
  • Say and Shout now carry an Option<String>. In main, a pattern can look inside two layers at once: Command::Say(Some(text)) prints the text, and Command::Say(None) answers "say what? Try /say hello". The compiler would refuse the program if either arm were missing.
  • last is an Option<String> that starts as None. /again matches on &last: the & borrows it, so last is still there for the next /again, and text inside the arm is a borrow too. After you say something, last = Some(said.text) stores it.
Chatterbox v0.5 after lesson 5.4: the whole program (green lines are new in this lesson)
You type
Sam
/say
/say   
/quit
Chatterbox prints (a real run)
Chatterbox v0.5
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: say what? Try /say hello
bot: say what? Try /say hello
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.rs31 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(Option<String>),
Shout(Option<String>),
Unknown(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,
}
}
 
/// 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(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 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 => match &last {
Some(text) => println!("bot: {}", reply(text)),
None => println!("bot: nothing to repeat yet"),
},
Command::History => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
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::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 = Some(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.

Notice that this program never uses unwrap. Every place a value might be missing is a match with a None arm that says something sensible. Chatterbox now has a Message with methods, a Command for every kind of line, and no empty string pretending to be nothing. The last lesson of this chapter looks harder at the patterns you have been writing in those arms, and gives match a few more tricks.

Try itYour turn: arg and owned in Chatterbox

This is the whole Chatterbox program with the bodies of arg and owned taken out. Write them again. arg gives back the text after the command word, or None when there is none (spaces alone do not count). owned turns an Option<&str> into an Option<String>.

This is the whole Chatterbox program with the bodies of arg and owned taken out. Write them again. arg gives back the text after the command word, or None when there is none (spaces alone do not count). owned turns an Option<&str> into an Option<String>.

// 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(Option<String>),
Shout(Option<String>),
Unknown(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> {
// Some(&str) becomes Some(String); None stays None
todo!()
}
 
/// 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(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> {
// Some(the text after the first space), or None if there is no real text
todo!()
}
 
/// 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 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 => match &last {
Some(text) => println!("bot: {}", reply(text)),
None => println!("bot: nothing to repeat yet"),
},
Command::History => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
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::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 = Some(said.text); // the text moves out of `said`, which is not used again
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (7): arg_keeps_every_word bare_command_has_no_arg arg_finds_the_text bare_say_parses_to_none only_spaces_is_no_arg owned_copies_some owned_keeps_none

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 are the two variants of <code>Option&lt;T&gt;</code>?Reveal
Some(value) when there is a value and None when there is not.
Why does Rust refuse to use an <code>Option&lt;&amp;str&gt;</code> where a <code>&amp;str</code> is expected?Reveal
Because the value might be missing. You have to say what happens for None first, with match or unwrap_or, so a missing value can never crash the program by surprise.
What does <code>unwrap_or("none")</code> do?Reveal
Returns the value inside Some, or the fallback you gave if it is None.

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

Next: 5.5 Patterns →

Questions people ask

Does Rust have null?

No. A value that might be missing has the type Option, which is either Some(value) or None, and the compiler makes you handle None before you can use the value.

What is the difference between unwrap and unwrap_or in Rust?

unwrap_or gives you the value or a fallback you choose, so it never crashes. unwrap gives you the value or stops the program with a panic when there is none.

Why not just use an empty string to mean nothing?

Because an empty string is also a real value. A bare /say and a /say followed by spaces both looked like an empty argument, and nothing forced the code to check. With Option, nothing is None, the type says it can happen, and the compiler makes every caller decide what to do about it.

Can Option hold any type?

Yes. The T in Option of T stands for any type, so an Option can hold borrowed text, a String, a number, a Message, or anything else that might be missing.

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