En bref. Un newtype (struct CompteId(u64)) donne un type distinct à une valeur qui n’était qu’un nombre : inverser deux arguments devient E0308 au lieu d’un virement vers le mauvais compte. Le type-state pousse l’idée jusqu’à l’état : Connexion<Fermee> et Connexion<Ouverte> sont deux types, et envoyer n’existe que sur le second. L’appel interdit ne déclenche pas d’erreur à l’exécution : il ne compile pas (E0599).
Le modèle en une phrase
Une règle qui vit dans votre tête peut être oubliée. Une règle qui vit dans le type est vérifiée à chaque compilation, sans coût à l’exécution.
Les deux articles précédents ont rendu les états explicites (enum) et l’absence obligatoire à traiter (Option). Celui-ci rend certaines erreurs impossibles à écrire.
In short. A newtype (struct CompteId(u64)) gives a distinct type to a value that used to be just a number: swapping two arguments becomes E0308 instead of a transfer to the wrong account. Type-state takes the idea up to state: Connexion<Fermee> and Connexion<Ouverte> (closed, open) are two types, and envoyer (“send”) only exists on the second. The forbidden call doesn’t fail at runtime: it doesn’t compile (E0599).
The model in one sentence
A rule that lives in your head can be forgotten. A rule that lives in the type is checked on every compilation, at no runtime cost.
The two previous articles made states explicit (enum) and absence mandatory to handle (Option). This one makes some mistakes impossible to write.
let c = Connexion::new("db:5432");c.envoyer("SELECT 1");
- Une connexion neuve est une
Connexion<Fermee>. Ce type n'a queouvrir:c.envoyer(…)donne E0599, the method was found for `Connexion<Ouverte>`.A new connection is aConnexion<Fermee>. That type only hasouvrir:c.envoyer(…)gives E0599, the method was found for `Connexion<Ouverte>`. ouvrir(self)consomme la connexion fermée et en rend une ouverte. On rebaptisec: l'ancienne valeur n'existe plus.ouvrir(self)consumes the closed connection and returns an open one. We shadowc: the old value no longer exists.- Sur
Connexion<Ouverte>,envoyerexiste. Ça compile, ça affichedb:5432 <- SELECT 1.OnConnexion<Ouverte>,envoyerexists. It compiles and printsdb:5432 <- SELECT 1. - Après
fermer(self), garder l'ancienne poignée ne sert à rien : elle a été déplacée. Réutiliserouvertedonne E0382.Afterfermer(self), keeping the old handle is useless: it was moved. Reusingouvertegives E0382.
Le newtype : des emplacements qui ont une forme
fn virement_brut(depuis: u64, vers: u64, montant: u64) { /* … */ }
let alice = 42;
let loyer = 85_000;
virement_brut(alice, loyer, 7);Ça compile, sans un avertissement : le loyer part vers le compte 85 000, et on vire 7 centimes. Pour le compilateur, trois u64 sont interchangeables. Enveloppons-les :
struct CompteId(u64);
struct Centimes(u64);
fn virement(depuis: CompteId, vers: CompteId, montant: Centimes) { /* … */ }
virement(CompteId(42), Centimes(85_000), CompteId(7));error[E0308]: arguments to this function are incorrect
--> src/main.rs:16:5
|
16 | virement(CompteId(42), Centimes(85_000), CompteId(7));
| ^^^^^^^^ ---------------- ----------- expected `Centimes`, found `CompteId`
| |
| expected `CompteId`, found `Centimes`
|
note: function defined here
--> src/main.rs:4:4
|
4 | fn virement(depuis: CompteId, vers: CompteId, montant: Centimes) {
| ^^^^^^^^
help: swap these arguments
|
16 - virement(CompteId(42), Centimes(85_000), CompteId(7));
16 + virement(CompteId(42), CompteId(7), Centimes(85_000));
|rustc trouve même la permutation. Et le prix à l’exécution est nul : size_of::<CompteId>() vaut 8, comme u64. C’est le second mode de l’animation.
Le type-state : la méthode qui n’existe pas
Une connexion doit être ouverte avant d’envoyer. Au lieu d’un booléen ouverte: bool vérifié à l’exécution, l’état devient un paramètre de type :
use std::marker::PhantomData;
struct Fermee;
struct Ouverte;
struct Connexion<Etat> {
adresse: String,
_etat: PhantomData<Etat>,
}
impl Connexion<Fermee> {
fn new(adresse: &str) -> Self {
Connexion { adresse: adresse.to_string(), _etat: PhantomData }
}
fn ouvrir(self) -> Connexion<Ouverte> {
Connexion { adresse: self.adresse, _etat: PhantomData }
}
}
impl Connexion<Ouverte> {
fn envoyer(&self, msg: &str) {
println!("{} <- {msg}", self.adresse);
}
fn fermer(self) -> Connexion<Fermee> {
Connexion { adresse: self.adresse, _etat: PhantomData }
}
} new ──▶ Connexion<Fermee> ──ouvrir(self)──▶ Connexion<Ouverte>
▲ · ouvrir · envoyer
│ · fermer
└──────────────fermer(self)──────────────┘Envoyer sur une connexion neuve :
let c = Connexion::new("db:5432");
c.envoyer("SELECT 1");error[E0599]: no method named `envoyer` found for struct `Connexion<Fermee>` in the current scope
--> src/main.rs:31:7
|
6 | struct Connexion<Etat> {
| ---------------------- method `envoyer` not found for this struct
...
31 | c.envoyer("SELECT 1");
| ^^^^^^^ method not found in `Connexion<Fermee>`
|
= note: the method was found for `Connexion<Ouverte>`La note dit tout : la méthode existe, mais pour l’autre état. Le chemin valide, let c = c.ouvrir(); c.envoyer("SELECT 1");, compile et affiche db:5432 <- SELECT 1. C’est le premier mode de l’animation.
Les transitions consomment l’ancien état
ouvrir et fermer prennent self par valeur. Garder l’ancienne poignée ne sert donc à rien :
let ouverte = fermee.ouvrir();
ouverte.envoyer("SELECT 1");
let _f = ouverte.fermer();
ouverte.envoyer("SELECT 2");error[E0382]: borrow of moved value: `ouverte`
--> src/main.rs:34:5
|
31 | let ouverte = fermee.ouvrir();
| ------- move occurs because `ouverte` has type `Connexion<Ouverte>`, which does not implement the `Copy` trait
32 | ouverte.envoyer("SELECT 1");
33 | let _f = ouverte.fermer();
| -------- `ouverte` moved due to this method call
34 | ouverte.envoyer("SELECT 2");
| ^^^^^^^ value borrowed here after move
|
note: `Connexion::<Ouverte>::fermer` takes ownership of the receiver `self`, which moves `ouverte`
--> src/main.rs:24:15
|
24 | fn fermer(self) -> Connexion<Fermee> {
| ^^^^C’est le move du tout premier article, mis au service d’une règle métier : « on n’envoie pas sur une connexion fermée » devient « la variable qui le permettrait n’existe plus ». Et PhantomData ne coûte rien : Connexion<Ouverte> fait 24 octets, exactement comme la String qu’elle contient.
Ce que l’image cache
- Un newtype perd les opérations du type enveloppé.
Centimes(100) + Centimes(250)donne E0369 cannot addCentimestoCentimestant qu’on n’implémente pasAdd. C’est un choix : additionner deux montants a un sens, additionner deuxCompteIdn’en a pas. - Le champ privé garde l’invariant. Si
CompteId(u64)a un champ privé et un constructeur qui valide, impossible de fabriquer un identifiant invalide hors du module (CompteId(0)donne E0423 après unuse, E0603 avec le chemin completbanque::CompteId(0)). - Le type-state suppose un état connu à la compilation. Une connexion dont l’état est lu dans une configuration revient à une enum et à un
match. - La cérémonie a un prix. Dix états et quarante transitions, c’est quarante méthodes et autant de types à lire. Si le bug évité est rare et bénin, un
assert!suffit. - Les bibliothèques le font déjà. Les builders qui n’exposent
build()qu’une fois les champs obligatoires remplis sont un type-state.
Pour aller plus loin
- Le volume 3, numéro 03 de The Rust Loop, Newtype & type-state, montre les invariants dans le type et le contre-exemple de la cérémonie (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), Option et unwrap. - The Rust Book, 20.3 : le pattern newtype
- Documentation de
PhantomData - Index des erreurs : E0599
Newtype: slots that have a shape
fn virement_brut(depuis: u64, vers: u64, montant: u64) { /* … */ }
let alice = 42;
let loyer = 85_000;
virement_brut(alice, loyer, 7);(virement is a bank transfer, depuis from, vers to, montant amount, loyer rent.) It compiles without a warning: the rent goes to account 85,000, and 7 cents are transferred. To the compiler, three u64s are interchangeable. Let’s wrap them:
struct CompteId(u64);
struct Centimes(u64);
fn virement(depuis: CompteId, vers: CompteId, montant: Centimes) { /* … */ }
virement(CompteId(42), Centimes(85_000), CompteId(7));error[E0308]: arguments to this function are incorrect
--> src/main.rs:16:5
|
16 | virement(CompteId(42), Centimes(85_000), CompteId(7));
| ^^^^^^^^ ---------------- ----------- expected `Centimes`, found `CompteId`
| |
| expected `CompteId`, found `Centimes`
|
note: function defined here
--> src/main.rs:4:4
|
4 | fn virement(depuis: CompteId, vers: CompteId, montant: Centimes) {
| ^^^^^^^^
help: swap these arguments
|
16 - virement(CompteId(42), Centimes(85_000), CompteId(7));
16 + virement(CompteId(42), CompteId(7), Centimes(85_000));
|rustc even finds the permutation. And the runtime price is zero: size_of::<CompteId>() is 8, like u64. That is the animation’s second mode.
Type-state: the method that doesn’t exist
A connection must be open before sending. Instead of an ouverte: bool flag checked at runtime, the state becomes a type parameter:
use std::marker::PhantomData;
struct Fermee;
struct Ouverte;
struct Connexion<Etat> {
adresse: String,
_etat: PhantomData<Etat>,
}
impl Connexion<Fermee> {
fn new(adresse: &str) -> Self {
Connexion { adresse: adresse.to_string(), _etat: PhantomData }
}
fn ouvrir(self) -> Connexion<Ouverte> {
Connexion { adresse: self.adresse, _etat: PhantomData }
}
}
impl Connexion<Ouverte> {
fn envoyer(&self, msg: &str) {
println!("{} <- {msg}", self.adresse);
}
fn fermer(self) -> Connexion<Fermee> {
Connexion { adresse: self.adresse, _etat: PhantomData }
}
} new ──▶ Connexion<Fermee> ──ouvrir(self)──▶ Connexion<Ouverte>
▲ · ouvrir · envoyer
│ · fermer
└──────────────fermer(self)──────────────┘Sending on a new connection:
let c = Connexion::new("db:5432");
c.envoyer("SELECT 1");error[E0599]: no method named `envoyer` found for struct `Connexion<Fermee>` in the current scope
--> src/main.rs:31:7
|
6 | struct Connexion<Etat> {
| ---------------------- method `envoyer` not found for this struct
...
31 | c.envoyer("SELECT 1");
| ^^^^^^^ method not found in `Connexion<Fermee>`
|
= note: the method was found for `Connexion<Ouverte>`The note says it all: the method exists, but for the other state. The valid path, let c = c.ouvrir(); c.envoyer("SELECT 1");, compiles and prints db:5432 <- SELECT 1. That is the animation’s first mode.
Transitions consume the old state
ouvrir and fermer take self by value. Keeping the old handle is therefore useless:
let ouverte = fermee.ouvrir();
ouverte.envoyer("SELECT 1");
let _f = ouverte.fermer();
ouverte.envoyer("SELECT 2");error[E0382]: borrow of moved value: `ouverte`
--> src/main.rs:34:5
|
31 | let ouverte = fermee.ouvrir();
| ------- move occurs because `ouverte` has type `Connexion<Ouverte>`, which does not implement the `Copy` trait
32 | ouverte.envoyer("SELECT 1");
33 | let _f = ouverte.fermer();
| -------- `ouverte` moved due to this method call
34 | ouverte.envoyer("SELECT 2");
| ^^^^^^^ value borrowed here after move
|
note: `Connexion::<Ouverte>::fermer` takes ownership of the receiver `self`, which moves `ouverte`
--> src/main.rs:24:15
|
24 | fn fermer(self) -> Connexion<Fermee> {
| ^^^^That is the move from the very first article, put to work for a business rule: “don’t send on a closed connection” becomes “the variable that would allow it no longer exists”. And PhantomData costs nothing: Connexion<Ouverte> is 24 bytes, exactly like the String it holds.
What the picture hides
- A newtype loses the wrapped type’s operations.
Centimes(100) + Centimes(250)gives E0369 cannot addCentimestoCentimesuntil you implementAdd. That is a choice: adding two amounts makes sense, adding twoCompteIds doesn’t. - A private field guards the invariant. If
CompteId(u64)has a private field and a validating constructor, nobody outside the module can build an invalid id (CompteId(0)gives E0423 after ause, E0603 with the full pathbanque::CompteId(0)). - Type-state assumes a state known at compile time. A connection whose state is read from configuration goes back to an enum and a
match. - The ceremony has a price. Ten states and forty transitions means forty methods and as many types to read. If the bug avoided is rare and harmless, an
assert!is enough. - Libraries already do it. Builders that only expose
build()once required fields are set are a type-state.
Going further
- Volume 3, issue 03 of The Rust Loop, Newtype & type-state, shows invariants in the type and the counter-example of ceremony (link at the bottom of the page).
- Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap. - The Rust Book, 20.3: the newtype pattern
PhantomDatadocumentation- Error index: E0599