En bref. Option<T> est une boîte fermée : pleine (Some(valeur)) ou vide (None). On ne lit pas un champ à travers la boîte, rustc refuse (E0609) et suggère .unwrap(). Cette suggestion compile, puis le jour où la boîte est vide, le programme s’arrête : called Option::unwrap() on a None value. Ouvrir la boîte, c’est décider quoi faire des deux cas.
Le modèle en une phrase
Une valeur qui peut manquer arrive dans une boîte fermée. Le type vous oblige à l’ouvrir ;
unwrapl’ouvre en pariant qu’elle est pleine.
Option n’a rien de magique : c’est une enum à deux variantes, Some(T) et None. Tout ce que l’article précédent disait du match exhaustif s’applique ici.
In short. Option<T> is a closed box: full (Some(value)) or empty (None). You can’t read a field through the box; rustc refuses (E0609) and suggests .unwrap(). That suggestion compiles, and then the day the box is empty, the program stops: called Option::unwrap() on a None value. Opening the box means deciding what to do in both cases.
The model in one sentence
A value that may be missing arrives in a closed box. The type forces you to open it;
unwrapopens it betting that it is full.
Option is nothing magic: it is an enum with two variants, Some(T) and None. Everything the previous article said about exhaustive match applies here.
let c = trouve(&clients, 1);println!("{}", c.nom);
trouverenvoie une boîte fermée,Option<&Client>. On ne lit pasnomà travers : E0609. rustc suggèrec.unwrap().nom.trouvereturns a closed box,Option<&Client>. You can't readnomthrough it: E0609. rustc suggestsc.unwrap().nom.- On suit la suggestion. Le client 1 existe :
unwrapouvre la boîte, en sort&Client, le programme afficheAda.Follow the suggestion. Client 1 exists:unwrapopens the box, takes out&Client, the program printsAda. - Même code, autre identifiant : le client 7 n'existe pas.
trouverenvoieNone, une boîte vide. Ça compile toujours.Same code, another id: client 7 doesn't exist.trouvereturnsNone, an empty box. It still compiles. unwrapouvre la boîte vide : panic, called `Option::unwrap()` on a `None` value, code de sortie 101.unwrapopens the empty box: panic, called `Option::unwrap()` on a `None` value, exit code 101.
La boîte fermée : E0609
On cherche un client par identifiant. Il peut ne pas exister, donc trouve renvoie un Option :
struct Client {
id: u32,
nom: String,
}
fn trouve(clients: &[Client], id: u32) -> Option<&Client> {
clients.iter().find(|c| c.id == id)
}
fn main() {
let clients = vec![Client { id: 1, nom: String::from("Ada") }];
let c = trouve(&clients, 7);
println!("{}", c.nom);
}error[E0609]: no field `nom` on type `Option<&Client>`
--> src/main.rs:13:22
|
13 | println!("{}", c.nom);
| ^^^ unknown field
|
help: one of the expressions' fields has a field of the same name
|
13 | println!("{}", c.unwrap().nom);
| +++++++++c n’est pas un client, c’est une boîte qui en contient peut-être un. Dans un langage avec null, ce code compilerait et planterait plus tard. Ici, l’absence est inscrite dans le type, et le compilateur refuse qu’on l’ignore. Même logique ailleurs : let total: u32 = v.iter().find(…) donne E0308 expected u32, found Option<&u32>.
La suggestion qui panique
Le help propose c.unwrap().nom. Appliquons-le :
let c = trouve(&clients, 7);
println!("{}", c.unwrap().nom);Ça compile. À l’exécution :
thread 'main' (…) panicked at src/main.rs:13:22:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceCode de sortie 101. La suggestion a réparé le type (on obtient bien un &Client), pas la question : que faire quand le client n’existe pas ? unwrap y répond « arrêter le programme ». C’est le premier mode de l’animation.
expect ne change que le message :
println!("{}", c.expect("client 7 absent de la base").nom);thread 'main' (…) panicked at src/main.rs:13:22:
client 7 absent de la baseOuvrir la boîte en prévoyant None
Quatre outils, du plus explicite au plus compact. Toutes les sorties ci-dessous viennent du même programme compilé avec rustc 1.100.
// 1. match : les deux cas, côte à côte
match trouve(&clients, 7) {
Some(c) => println!("{}", c.nom),
None => println!("aucun client 7"),
}
// → aucun client 7
// 2. let-else : le chemin principal reste à plat
fn salue(clients: &[Client], id: u32) -> String {
let Some(c) = trouve(clients, id) else {
return String::from("inconnu");
};
format!("bonjour {}", c.nom)
}
// salue(&clients, 7) → "inconnu"
// 3. ? : on rend None à l'appelant
fn nom_du_parrain(clients: &[Client], id: u32) -> Option<&str> {
let c = trouve(clients, id)?;
let p = trouve(clients, c.parrain?)?;
Some(&p.nom)
}
// client 2 parrainé par 1 → Some("Ada") ; client 1 sans parrain → None ; client 7 → None
// 4. une valeur par défaut
let nom = trouve(&clients, 7).map(|c| c.nom.as_str()).unwrap_or("anonyme");
// → anonyme(Pour le 3, Client a gagné un champ parrain: Option<u32>.) Oublier le bras None du match donne E0004 non-exhaustive patterns: None not covered : la règle de l’article précédent, appliquée à Option. C’est le second mode de l’animation.
trouve(&clients, id) : Option<&Client>
│
├── Some(c) ──▶ on continue avec c
│
└── None ─────▶ match : un bras dédié
let-else : return / break / continue
? : return None à l'appelant
unwrap_or : une valeur de repli
unwrap : panic (code 101)? a une condition : la fonction doit elle-même renvoyer Option (ou Result). Dans main, v.first()? donne E0277 the ? operator can only be used in a function that returns Result or Option.
Ce que l’image cache
unwrapa sa place. Dans un test, un prototype, ou quandNoneest impossible par construction. Écrivez alorsexpectavec la raison : c’est la première ligne qu’on lira dans le log.- La boîte est souvent gratuite. Mesuré avec
size_of(cible 64 bits) :Option<&Client>etOption<Box<u8>>font 8 octets, comme la référence seule, car une référence n’est jamais nulle etNoneprend cette valeur.Option<u32>fait 8 octets contre 4 pouru32. if let Some(c) = …traite un seul cas et ignore l’autre en silence. Parfait pour « s’il y en a un, fais ceci ».- Les méthodes évitent beaucoup de
match:map,and_then,unwrap_or_default,ok_or(pour passer àResult),as_deref(deOption<String>àOption<&str>). Optiondit qu’une valeur manque, pas pourquoi. Quand la raison compte, c’estResult, que la série retrouve au volume 4.
Pour aller plus loin
- Le volume 3, numéro 02 de The Rust Loop, Option, ou l’absence de null, détaille le coût de
unwrapet les combinateurs (lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004). - The Rust Book, 6.1 : The Option Enum
- Documentation de
std::option - Index des erreurs : E0609
The closed box: E0609
We look up a customer by id. It may not exist, so trouve (“find”) returns an Option:
struct Client {
id: u32,
nom: String,
}
fn trouve(clients: &[Client], id: u32) -> Option<&Client> {
clients.iter().find(|c| c.id == id)
}
fn main() {
let clients = vec![Client { id: 1, nom: String::from("Ada") }];
let c = trouve(&clients, 7);
println!("{}", c.nom);
}error[E0609]: no field `nom` on type `Option<&Client>`
--> src/main.rs:13:22
|
13 | println!("{}", c.nom);
| ^^^ unknown field
|
help: one of the expressions' fields has a field of the same name
|
13 | println!("{}", c.unwrap().nom);
| +++++++++c is not a customer, it is a box that might contain one. In a language with null, this code would compile and crash later. Here, absence is written into the type, and the compiler refuses to let you ignore it. Same logic elsewhere: let total: u32 = v.iter().find(…) gives E0308 expected u32, found Option<&u32>.
The suggestion that panics
The help suggests c.unwrap().nom. Let’s apply it:
let c = trouve(&clients, 7);
println!("{}", c.unwrap().nom);It compiles. At runtime:
thread 'main' (…) panicked at src/main.rs:13:22:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceExit code 101. The suggestion fixed the type (you do get a &Client), not the question: what should happen when the customer doesn’t exist? unwrap answers “stop the program”. That is the animation’s first mode.
expect only changes the message:
println!("{}", c.expect("client 7 absent de la base").nom);thread 'main' (…) panicked at src/main.rs:13:22:
client 7 absent de la baseOpening the box, planning for None
Four tools, from most explicit to most compact. Every output below comes from the same program compiled with rustc 1.100.
// 1. match: both cases, side by side
match trouve(&clients, 7) {
Some(c) => println!("{}", c.nom),
None => println!("aucun client 7"),
}
// → aucun client 7
// 2. let-else: the main path stays flat
fn salue(clients: &[Client], id: u32) -> String {
let Some(c) = trouve(clients, id) else {
return String::from("inconnu");
};
format!("bonjour {}", c.nom)
}
// salue(&clients, 7) → "inconnu"
// 3. ?: hand None back to the caller
fn nom_du_parrain(clients: &[Client], id: u32) -> Option<&str> {
let c = trouve(clients, id)?;
let p = trouve(clients, c.parrain?)?;
Some(&p.nom)
}
// client 2 referred by 1 → Some("Ada"); client 1 with no referrer → None; client 7 → None
// 4. a default value
let nom = trouve(&clients, 7).map(|c| c.nom.as_str()).unwrap_or("anonyme");
// → anonyme(For #3, Client gained a parrain: Option<u32> field, “referrer”.) Forgetting the None arm of the match gives E0004 non-exhaustive patterns: None not covered: the previous article’s rule, applied to Option. That is the animation’s second mode.
trouve(&clients, id) : Option<&Client>
│
├── Some(c) ──▶ carry on with c
│
└── None ─────▶ match : a dedicated arm
let-else : return / break / continue
? : return None to the caller
unwrap_or : a fallback value
unwrap : panic (exit 101)? has one condition: the function itself must return Option (or Result). In main, v.first()? gives E0277 the ? operator can only be used in a function that returns Result or Option.
What the picture hides
unwraphas its place. In a test, a prototype, or whenNoneis impossible by construction. Then writeexpectwith the reason: it is the first line anyone will read in the log.- The box is often free. Measured with
size_of(64-bit target):Option<&Client>andOption<Box<u8>>are 8 bytes, like the bare reference, because a reference is never null andNoneuses that value.Option<u32>is 8 bytes versus 4 foru32. if let Some(c) = …handles one case and silently ignores the other. Perfect for “if there is one, do this”.- Methods save a lot of
match:map,and_then,unwrap_or_default,ok_or(to move toResult),as_deref(fromOption<String>toOption<&str>). Optionsays a value is missing, not why. When the reason matters, that isResult, which the series meets in volume 4.
Going further
- Volume 3, issue 02 of The Rust Loop, Option, or the absence of null, covers the cost of
unwrapand the combinators (link at the bottom of the page). - Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004). - The Rust Book, 6.1: The Option Enum
std::optiondocumentation- Error index: E0609