En bref. Une enum Rust n’est pas une liste de constantes : c’est une seule forme parmi plusieurs, et chaque forme porte ses propres données. Un match doit traiter chaque forme. Ajoutez une variante sans la traiter : le code ne compile plus (E0004) et rustc vous montre l’endroit. Mettez un joker _ : il compile, et la nouvelle variante reçoit un comportement que personne n’a choisi.
Le modèle en une phrase
Une valeur d’enum est exactement une de ses variantes. Le
matchest un aiguillage avec une voie par variante, et le compilateur vérifie qu’aucune voie ne manque.
Le volume 2 a fini sur la possession comme réponse aux problèmes de durée. Le volume 3 change de terrain : modéliser le domaine pour que les états impossibles ne s’écrivent pas.
In short. A Rust enum is not a list of constants: it is exactly one shape among several, and each shape carries its own data. A match must handle every shape. Add a variant without handling it: the code no longer compiles (E0004) and rustc points you to the spot. Use a _ wildcard: it compiles, and the new variant gets a behaviour nobody chose.
The model in one sentence
An enum value is exactly one of its variants. A
matchis a switchyard with one track per variant, and the compiler checks that no track is missing.
Volume 2 ended with ownership as the answer to lifetime problems. Volume 3 changes ground: model the domain so that impossible states cannot be written.
enum Paiement {Carte { numero: String, titulaire: String },Virement { iban: String },Especes,}match p {Paiement::Carte { .. } => 150,Paiement::Virement { .. } => 0,Paiement::Especes => 0,}
- Un
Paiementest exactement l'une de ces trois formes, chacune avec ses propres données. Lematcha un bras par forme.APaiementis exactly one of these three shapes, each with its own data. Thematchhas one arm per shape. - Pour
Paiement::Virement { iban }, un seul bras s'exécute. Les autres formes n'existent pas pour cette valeur.ForPaiement::Virement { iban }, exactly one arm runs. The other shapes don't exist for this value. - On ajoute une forme à l'enum :
Crypto.Add a shape to the enum:Crypto. - Aucun bras ne la traite. Le code ne compile plus : E0004 non-exhaustive patterns: `&Paiement::Crypto { .. }` not covered.No arm handles it. The code no longer compiles: E0004 non-exhaustive patterns: `&Paiement::Crypto { .. }` not covered.
Une forme, et seulement une
struct : tous les champs à la fois enum : une seule variante à la fois
┌───────────────────────────────┐ ┌──────────────────────────────┐
│ en_cours : bool (×2) │ │ Chargement │
│ donnees : Option<String>(×2) │ ├──────────────────────────────┤
│ erreur : Option<String>(×2) │ │ Pret(String) │
└───────────────────────────────┘ ├──────────────────────────────┤
2 × 2 × 2 = 8 combinaisons │ Echec(String) │
dont 5 n'ont aucun sens └──────────────────────────────┘
3 états, les 3 voulusLa version struct compile très bien avec un état absurde :
struct EtatFlou {
en_cours: bool,
donnees: Option<String>,
erreur: Option<String>,
}
let absurde = EtatFlou {
en_cours: true,
donnees: Some("ok".into()),
erreur: Some("échec".into()),
};
// affiche : true Some("ok") Some("échec")Chargement en cours, réussi et échoué à la fois. Avec l’enum, cet état n’a pas d’écriture :
enum Etat {
Chargement,
Pret(String),
Echec(String),
}C’est pour ça qu’on appelle l’enum un type somme (ses états s’additionnent : 1 + 1 + 1) et la struct un type produit (ses champs se multiplient). Bonus mesuré avec size_of sur cible 64 bits : Etat occupe 32 octets, EtatFlou 56. Une enum fait la taille de sa plus grande variante (ici une String, 24 octets) plus de quoi savoir laquelle est active.
Le match oublié : E0004
Un moyen de paiement, et les frais associés :
enum Paiement {
Carte { numero: String, titulaire: String },
Virement { iban: String },
Especes,
Crypto { reseau: String },
}
fn frais(p: &Paiement) -> u32 {
match p {
Paiement::Carte { .. } => 150,
Paiement::Virement { .. } => 0,
Paiement::Especes => 0,
}
}Crypto vient d’être ajoutée à l’enum ; frais n’a pas suivi. rustc 1.100 :
error[E0004]: non-exhaustive patterns: `&Paiement::Crypto { .. }` not covered
--> src/main.rs:9:11
|
9 | match p {
| ^ pattern `&Paiement::Crypto { .. }` not covered
|
note: `Paiement` defined here
--> src/main.rs:1:6
|
1 | enum Paiement {
| ^^^^^^^^
...
5 | Crypto { reseau: String },
| ------ not covered
= note: the matched value is of type `&Paiement`
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 ~ Paiement::Especes => 0,
13 ~ &Paiement::Crypto { .. } => todo!(),
|Cette erreur est une liste de tâches. Dans une base de code réelle, ajouter une variante fait apparaître un E0004 dans chaque match concerné : le compilateur fait l’inventaire à votre place. C’est le premier mode de l’animation.
Le joker qui se tait
Le réflexe pour « simplifier » :
fn frais(p: &Paiement) -> u32 {
match p {
Paiement::Carte { .. } => 150,
_ => 0,
}
}
fn main() {
let p = Paiement::Crypto { reseau: String::from("lightning") };
println!("frais : {}", frais(&p));
}Ça compile, et ça affiche frais : 0. Le match est exhaustif : _ couvre tout ce qui reste, y compris ce qui n’existait pas quand on l’a écrit. La crypto est devenue gratuite sans que personne l’ait décidé, et le compilateur n’avait aucune raison de le signaler. C’est le second mode de l’animation.
Règle pratique : sur une enum de votre code, nommez les variantes. Gardez _ pour les domaines ouverts (un entier, une chaîne) ou pour un bras qui veut réellement dire « tout le reste, y compris le futur ».
Déstructurer : le bras lie les données
Un bras ne fait pas que choisir, il ouvre la variante et nomme ses champs :
fn decrit(p: &Paiement) -> String {
match p {
Paiement::Carte { titulaire, .. } => format!("carte de {titulaire}"),
Paiement::Virement { iban } => format!("virement depuis {iban}"),
Paiement::Especes => String::from("espèces"),
}
}
// decrit(&Paiement::Virement { iban: "FR76…".into() }) → "virement depuis FR76…"iban n’existe que dans le bras Virement. Impossible de lire l’IBAN d’un paiement en espèces : il n’y a pas de champ à lire. .. ignore les champs qu’on ne nomme pas. Comme p est une référence, titulaire et iban sont des &String : le match emprunte, il ne déplace rien.
Ce que l’image cache
- E0004 ne concerne pas que les enums. Un
matchsur unu8avec0..=9et10..=20donnenon-exhaustive patterns: \21_u8..=u8::MAX` not covered`. Le compilateur raisonne sur toutes les valeurs du type. Optionest une enum ordinaire.Some/Noneobéit aux mêmes règles,Result(Ok/Err) aussi ;Optionest le numéro suivant du volume.if lettraite une seule variante et ignore les autres en silence, comme un joker. Pratique pour un cas, risqué comme logique métier.#[non_exhaustive]sur une enum de bibliothèque impose aux utilisateurs extérieurs un bras_: l’auteur se réserve le droit d’ajouter des variantes sans casser leur code.- Les bras sont testés dans l’ordre. Un
_placé en premier avale tout ; rustc avertit alors que les bras suivants sont inatteignables.
Pour aller plus loin
- Le volume 3, numéro 01 de The Rust Loop, Enums & pattern matching, modélise un domaine complet avec des enums (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static. - The Rust Book, chapitre 6 : Enums and Pattern Matching
- Index des erreurs : E0004
One shape, and only one
struct: all fields at once enum: exactly one variant at a time
┌───────────────────────────────┐ ┌──────────────────────────────┐
│ en_cours : bool (×2) │ │ Chargement │
│ donnees : Option<String>(×2) │ ├──────────────────────────────┤
│ erreur : Option<String>(×2) │ │ Pret(String) │
└───────────────────────────────┘ ├──────────────────────────────┤
2 × 2 × 2 = 8 combinations │ Echec(String) │
5 of which make no sense └──────────────────────────────┘
3 states, all 3 intended(en_cours means “in progress”, donnees “data”, erreur “error”; Chargement, Pret, Echec are Loading, Ready, Failed.) The struct version happily compiles an absurd state:
struct EtatFlou {
en_cours: bool,
donnees: Option<String>,
erreur: Option<String>,
}
let absurde = EtatFlou {
en_cours: true,
donnees: Some("ok".into()),
erreur: Some("échec".into()),
};
// prints: true Some("ok") Some("échec")Loading, succeeded and failed all at once. With the enum, that state has no spelling:
enum Etat {
Chargement,
Pret(String),
Echec(String),
}That is why an enum is called a sum type (its states add up: 1 + 1 + 1) and a struct a product type (its fields multiply). Bonus, measured with size_of on a 64-bit target: Etat takes 32 bytes, EtatFlou 56. An enum is the size of its largest variant (here a String, 24 bytes) plus room to know which one is active.
The forgotten match: E0004
A payment method and its fees (Carte card, Virement bank transfer, Especes cash, frais fees):
enum Paiement {
Carte { numero: String, titulaire: String },
Virement { iban: String },
Especes,
Crypto { reseau: String },
}
fn frais(p: &Paiement) -> u32 {
match p {
Paiement::Carte { .. } => 150,
Paiement::Virement { .. } => 0,
Paiement::Especes => 0,
}
}Crypto was just added to the enum; frais didn’t follow. rustc 1.100:
error[E0004]: non-exhaustive patterns: `&Paiement::Crypto { .. }` not covered
--> src/main.rs:9:11
|
9 | match p {
| ^ pattern `&Paiement::Crypto { .. }` not covered
|
note: `Paiement` defined here
--> src/main.rs:1:6
|
1 | enum Paiement {
| ^^^^^^^^
...
5 | Crypto { reseau: String },
| ------ not covered
= note: the matched value is of type `&Paiement`
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 ~ Paiement::Especes => 0,
13 ~ &Paiement::Crypto { .. } => todo!(),
|This error is a to-do list. In a real codebase, adding a variant raises an E0004 in every relevant match: the compiler takes inventory for you. That is the animation’s first mode.
The wildcard that stays quiet
The reflex to “simplify”:
fn frais(p: &Paiement) -> u32 {
match p {
Paiement::Carte { .. } => 150,
_ => 0,
}
}
fn main() {
let p = Paiement::Crypto { reseau: String::from("lightning") };
println!("frais : {}", frais(&p));
}It compiles and prints frais : 0. The match is exhaustive: _ covers everything left, including what didn’t exist when it was written. Crypto became free without anyone deciding so, and the compiler had no reason to flag it. That is the animation’s second mode.
Rule of thumb: on an enum from your own code, name the variants. Keep _ for open domains (an integer, a string) or for an arm that truly means “everything else, including the future”.
Destructuring: the arm binds the data
An arm doesn’t just choose, it opens the variant and names its fields:
fn decrit(p: &Paiement) -> String {
match p {
Paiement::Carte { titulaire, .. } => format!("carte de {titulaire}"),
Paiement::Virement { iban } => format!("virement depuis {iban}"),
Paiement::Especes => String::from("espèces"),
}
}
// decrit(&Paiement::Virement { iban: "FR76…".into() }) → "virement depuis FR76…"iban only exists inside the Virement arm. You cannot read the IBAN of a cash payment: there is no field to read. .. ignores the fields you don’t name. Since p is a reference, titulaire and iban are &String: the match borrows, it moves nothing.
What the picture hides
- E0004 is not only about enums. A
matchon au8with0..=9and10..=20givesnon-exhaustive patterns: \21_u8..=u8::MAX` not covered`. The compiler reasons over every value of the type. Optionis an ordinary enum.Some/Nonefollows the same rules, and so doesResult(Ok/Err);Optionis the volume’s next issue.if lethandles a single variant and silently ignores the others, like a wildcard. Handy for one case, risky as business logic.#[non_exhaustive]on a library enum forces outside users to write a_arm: the author keeps the right to add variants without breaking their code.- Arms are tried in order. A
_placed first swallows everything; rustc then warns that the following arms are unreachable.
Going further
- Volume 3, issue 01 of The Rust Loop, Enums & pattern matching, models a full domain with enums (link at the bottom of the page).
- Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static. - The Rust Book, chapter 6: Enums and Pattern Matching
- Error index: E0004