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.
$ cargo run
the argument is hello
no argumentline.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
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".
What does this print?
hi | nonehi |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.
argreplacesrest_of. It returnsOption<&str>:Some("hello")for/say hello, andNonefor a bare/sayor one followed only by spaces. It isfind_command_argfrom above, plus atrim()so that spaces alone do not count as an argument.ownedturns a borrowedOption<&str>into an ownedOption<String>. TheCommandhas 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.SayandShoutnow carry anOption<String>. Inmain, a pattern can look inside two layers at once:Command::Say(Some(text))prints the text, andCommand::Say(None)answers "say what? Try /say hello". The compiler would refuse the program if either arm were missing.lastis anOption<String>that starts asNone./againmatches on&last: the&borrows it, solastis still there for the next/again, andtextinside the arm is a borrow too. After you say something,last = Some(said.text)stores it.
Sam /say /say /quit
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)
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.
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>.
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.
Say it out loud, then reveal
What are the two variants of <code>Option<T></code>?Reveal
Some(value) when there is a value and None when there is not.Why does Rust refuse to use an <code>Option<&str></code> where a <code>&str</code> is expected?Reveal
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
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.
Go deeper
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.