« no method named … found for struct » (E0599) : newtype et type-state en Rust, le modèle mental "no method named … found for struct" (E0599): newtype and type-state in Rust, the mental model

Connexion<Fermee> et Connexion<Ouverte> sont deux types : envoyer n'existe pas sur une connexion fermée (E0599). CompteId et Centimes ne s'échangent pas (E0308). Animation, sorties réelles de rustc, coût mesuré : zéro octet.Connexion<Fermee> and Connexion<Ouverte> are two types: envoyer doesn't exist on a closed connection (E0599). CompteId and Centimes can't be swapped (E0308). Animation, real rustc output, measured cost: zero bytes.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
TypesTypes
PubliéPublished

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");
L'état est dans le typeThe state lives in the typeConnexion<Fermee> n'a pas envoyerConnexion<Fermee> has no envoyerConnexion<Fermee>new(adresse)ouvrir(self)Connexion<Ouverte>envoyer(&self, msg)fermer(self)ouvrirfermerenvoyer ?couverte (moved)E0599 · envoyer n'existe pas sur Connexion<Fermee>E0599 · envoyer doesn't exist on Connexion<Fermee>vérifié avec rustc 1.100checked with rustc 1.100
  1. Une connexion neuve est une Connexion<Fermee>. Ce type n'a que ouvrir : c.envoyer(…) donne E0599, the method was found for `Connexion<Ouverte>`.A new connection is a Connexion<Fermee>. That type only has ouvrir: c.envoyer(…) gives E0599, the method was found for `Connexion<Ouverte>`.
  2. ouvrir(self) consomme la connexion fermée et en rend une ouverte. On rebaptise c : l'ancienne valeur n'existe plus.ouvrir(self) consumes the closed connection and returns an open one. We shadow c: the old value no longer exists.
  3. Sur Connexion<Ouverte>, envoyer existe. Ça compile, ça affiche db:5432 <- SELECT 1.On Connexion<Ouverte>, envoyer exists. It compiles and prints db:5432 <- SELECT 1.
  4. Après fermer(self), garder l'ancienne poignée ne sert à rien : elle a été déplacée. Réutiliser ouverte donne E0382.After fermer(self), keeping the old handle is useless: it was moved. Reusing ouverte gives E0382.
Type-state en Rust : Connexion<Fermee> et Connexion<Ouverte> sont deux types distincts. envoyer n'existe que sur l'état ouvert (sinon E0599), et chaque transition consomme l'état précédent.Type-state in Rust: Connexion<Fermee> and Connexion<Ouverte> are two distinct types. envoyer only exists on the open state (otherwise E0599), and each transition consumes the previous state.

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 add Centimes to Centimes tant qu’on n’implémente pas Add. C’est un choix : additionner deux montants a un sens, additionner deux CompteId n’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 un use, E0603 avec le chemin complet banque::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

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 add Centimes to Centimes until you implement Add. That is a choice: adding two amounts makes sense, adding two CompteIds 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 a use, E0603 with the full path banque::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

Questions fréquentesFrequently asked questions

Que signifie l'erreur Rust E0599 « no method named … found for struct » ?What does Rust error E0599 "no method named … found for struct" mean?

Le type de la valeur n'a pas de méthode de ce nom. Avec des génériques, rustc précise souvent où elle existe : « the method was found for `Connexion<Ouverte>` ». Dans un type-state, c'est voulu : la méthode n'est définie que pour l'état où l'appel a un sens.The value's type has no method by that name. With generics, rustc often says where it does exist: "the method was found for `Connexion<Ouverte>`". In a type-state, that is intended: the method is only defined for the state where the call makes sense.

Qu'est-ce qu'un newtype en Rust ?What is a newtype in Rust?

Une struct tuple à un seul champ, comme struct CompteId(u64). Elle a la même taille que le type enveloppé (8 octets ici, mesuré avec size_of) mais c'est un type distinct : on ne peut plus passer un montant là où un identifiant de compte est attendu (E0308).A one-field tuple struct, like struct CompteId(u64). It has the same size as the wrapped type (8 bytes here, measured with size_of) but it is a distinct type: you can no longer pass an amount where an account id is expected (E0308).

Qu'est-ce que le pattern type-state ?What is the type-state pattern?

Représenter chaque état d'un objet par un type distinct, souvent via un paramètre générique (Connexion<Fermee>, Connexion<Ouverte>). Chaque état n'a que les méthodes valides, et les transitions prennent self par valeur : l'ancien état est consommé et ne peut plus servir (E0382).Representing each state of an object with a distinct type, often via a generic parameter (Connexion<Fermee>, Connexion<Ouverte>). Each state has only its valid methods, and transitions take self by value: the old state is consumed and can't be used again (E0382).

Le type-state a-t-il un coût à l'exécution ?Does type-state have a runtime cost?

Non pour la mémoire : PhantomData occupe zéro octet, Connexion<Ouverte> fait 24 octets comme la String qu'elle contient. Le coût est dans le code : une impl par état, et un état choisi à l'exécution (lu dans un fichier, par exemple) demande de revenir à une enum.Not in memory: PhantomData takes zero bytes, Connexion<Ouverte> is 24 bytes like the String it holds. The cost is in the code: one impl per state, and a state chosen at runtime (read from a file, for example) means going back to an enum.

Quand ne pas utiliser newtype ou type-state ?When should I not use newtype or type-state?

Quand la cérémonie coûte plus que le bug évité : un identifiant utilisé à un seul endroit, un état qui ne change qu'à l'exécution, une machine à dix états et quarante transitions. Le newtype perd aussi les opérateurs : Centimes + Centimes donne E0369 tant qu'on n'implémente pas Add.When the ceremony costs more than the bug it prevents: an id used in one place, a state that only changes at runtime, a machine with ten states and forty transitions. A newtype also loses operators: Centimes + Centimes gives E0369 until you implement Add.

RustNewtypeType-stateE0599E0308Modèle mental

← Tous les articlesAll articles