« called Option::unwrap() on a None value » : Option en Rust, le modèle mental "called Option::unwrap() on a None value": Option in Rust, the mental model

Option est une boîte fermée, pleine ou vide. On ne lit pas un champ à travers (E0609), et rustc suggère unwrap, qui panique sur None. Animation, sorties réelles de rustc, et les quatre façons d'ouvrir la boîte sans paniquer.Option is a closed box, full or empty. You can't read a field through it (E0609), and rustc suggests unwrap, which panics on None. Animation, real rustc output, and four ways to open the box without panicking.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
TypesTypes
PubliéPublished

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 ; unwrap l’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; unwrap opens 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);
Une boîte, pleine ou videA box, full or emptyunwrap parie que la boîte est pleineunwrap bets the box is fulltrouve(&clients, 1) -> Option<&Client>Somenom: "Ada"videemptyc.nomc.nomhelp : c.unwrap().nomhelp: c.unwrap().nomE0609 · no field `nom` on type `Option<&Client>`E0609 · no field `nom` on type `Option<&Client>`vérifié avec rustc 1.100checked with rustc 1.100
  1. trouve renvoie une boîte fermée, Option<&Client>. On ne lit pas nom à travers : E0609. rustc suggère c.unwrap().nom.trouve returns a closed box, Option<&Client>. You can't read nom through it: E0609. rustc suggests c.unwrap().nom.
  2. On suit la suggestion. Le client 1 existe : unwrap ouvre la boîte, en sort &Client, le programme affiche Ada.Follow the suggestion. Client 1 exists: unwrap opens the box, takes out &Client, the program prints Ada.
  3. Même code, autre identifiant : le client 7 n'existe pas. trouve renvoie None, une boîte vide. Ça compile toujours.Same code, another id: client 7 doesn't exist. trouve returns None, an empty box. It still compiles.
  4. unwrap ouvre la boîte vide : panic, called `Option::unwrap()` on a `None` value, code de sortie 101.unwrap opens the empty box: panic, called `Option::unwrap()` on a `None` value, exit code 101.
Option en Rust : une boîte fermée, pleine (Some) ou vide (None). unwrap l'ouvre à l'aveugle et panique sur None : called `Option::unwrap()` on a `None` value.Option in Rust: a closed box, full (Some) or empty (None). unwrap opens it blindly and panics on None: called `Option::unwrap()` on a `None` value.

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 backtrace

Code 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 base

Ouvrir 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

  • unwrap a sa place. Dans un test, un prototype, ou quand None est impossible par construction. Écrivez alors expect avec 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> et Option<Box<u8>> font 8 octets, comme la référence seule, car une référence n’est jamais nulle et None prend cette valeur. Option<u32> fait 8 octets contre 4 pour u32.
  • 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 (de Option<String> à Option<&str>).
  • Option dit qu’une valeur manque, pas pourquoi. Quand la raison compte, c’est Result, que la série retrouve au volume 4.

Pour aller plus loin

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 backtrace

Exit 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 base

Opening 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

  • unwrap has its place. In a test, a prototype, or when None is impossible by construction. Then write expect with 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> and Option<Box<u8>> are 8 bytes, like the bare reference, because a reference is never null and None uses that value. Option<u32> is 8 bytes versus 4 for u32.
  • 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 to Result), as_deref (from Option<String> to Option<&str>).
  • Option says a value is missing, not why. When the reason matters, that is Result, which the series meets in volume 4.

Going further

Questions fréquentesFrequently asked questions

Que signifie « called `Option::unwrap()` on a `None` value » ?What does "called `Option::unwrap()` on a `None` value" mean?

Le programme a appelé unwrap sur un Option qui valait None. unwrap n'a rien à renvoyer, alors il déclenche un panic : le thread s'arrête, et si c'est main, le programme sort avec le code 101. Le message indique le fichier, la ligne et la colonne de l'appel.The program called unwrap on an Option that was None. unwrap has nothing to return, so it panics: the thread stops, and if it is main, the program exits with code 101. The message gives the file, line and column of the call.

Comment éviter unwrap sur un Option en Rust ?How do I avoid unwrap on an Option in Rust?

Traitez les deux cas : match avec un bras Some et un bras None, if let pour un seul cas, let-else pour sortir tôt, l'opérateur ? pour renvoyer None à l'appelant, ou unwrap_or / map pour une valeur par défaut. unwrap reste acceptable quand None est vraiment impossible, de préférence avec expect et une raison.Handle both cases: match with a Some arm and a None arm, if let for a single case, let-else to leave early, the ? operator to return None to the caller, or unwrap_or / map for a default value. unwrap is still fine when None is truly impossible, preferably as expect with a reason.

Pourquoi rustc suggère-t-il unwrap si c'est dangereux ?Why does rustc suggest unwrap if it is dangerous?

Pour E0609 (no field on type Option<&Client>), rustc remarque que le contenu de l'Option possède le champ demandé et propose le chemin le plus court pour l'atteindre : c.unwrap().nom. La suggestion corrige le type, pas la logique ; c'est à vous de décider ce qui se passe quand l'Option est vide.For E0609 (no field on type Option<&Client>), rustc notices that the Option's content has the requested field and suggests the shortest way to reach it: c.unwrap().nom. The suggestion fixes the type, not the logic; deciding what happens when the Option is empty is up to you.

Quelle différence entre unwrap et expect ?What is the difference between unwrap and expect?

Aucune sur le comportement : les deux paniquent sur None. expect remplace le message générique par le vôtre (par exemple « client 7 absent de la base »). Écrivez-y pourquoi None ne devrait pas arriver : c'est la première chose qu'on lira dans le log.None in behaviour: both panic on None. expect replaces the generic message with yours (for example "client 7 absent de la base"). Write in it why None should not happen: it is the first thing anyone will read in the log.

Option coûte-t-il de la mémoire en Rust ?Does Option cost memory in Rust?

Parfois zéro. Mesuré avec size_of sur cible 64 bits : Option<&Client> et Option<Box<u8>> font 8 octets, comme la référence seule, car une référence n'est jamais nulle et None prend cette valeur. Option<u32> fait 8 octets contre 4 pour u32, car il faut de la place pour le discriminant.Sometimes zero. Measured with size_of on a 64-bit target: Option<&Client> and Option<Box<u8>> are 8 bytes, like the bare reference, because a reference is never null and None uses that value. Option<u32> is 8 bytes versus 4 for u32, since the discriminant needs room.

RustOptionunwrappanicE0609Modèle mental

← Tous les articlesAll articles