En bref. Le générique imprime une copie par type : il ne sait pas mélanger un Cercle et un Rect dans un même Vec. dyn Surface fait l’inverse. Il efface le type et retrouve la bonne méthode à l’exécution, grâce à la vtable. Cela coûte une indirection et l’inlining, et trois refus en découlent : the size cannot be known (E0277), the trait is not dyn compatible (E0038) et le 'static implicite.
Le modèle en une phrase
dyn Traitest une valeur dont le type a été effacé ; ce qu’il en reste tient dans un pointeur gras, un mot vers la valeur et un vers la vtable de son type, et tout ce que la vtable ne peut pas décrire est refusé.
Générique et dyn répondent à deux questions opposées. Si le type est unique et connu à cet endroit du code, le générique donne un appel direct et gratuit. Si plusieurs types doivent cohabiter, ou si le type n’est connu qu’à l’exécution, il faut dyn, et son prix est justifié.
In short. The generic prints one copy per type: it can’t mix a Cercle and a Rect in one Vec. dyn Surface does the opposite. It erases the type and finds the right method at runtime, through the vtable. That costs an indirection and inlining, and three refusals follow from it: the size cannot be known (E0277), the trait is not dyn compatible (E0038) and the implicit 'static.
The model in one sentence
dyn Traitis a value whose type has been erased; what remains fits in a fat pointer, one word to the value and one to its type’s vtable, and anything the vtable can’t describe is refused.
Generic and dyn answer two opposite questions. If the type is unique and known at this point in the code, the generic gives a direct, free call. If several types must live together, or the type is only known at runtime, you need dyn, and its price is earned.
fn total<T: Surface>(formes: &[T]) -> f64 { … }let formes = vec![Cercle { r: 1.0 }, Rect { l: 2.0, h: 3.0 }];
- Un générique a un seul type par copie.
vec![Cercle, Rect]demande deux types dans une même collection : rustc fixe le type au premier élément et refuse le second. E0308, expected `Cercle`, found `Rect`.A generic has a single type per copy.vec![Cercle, Rect]asks for two types in one collection: rustc fixes the type at the first element and rejects the second. E0308, expected `Cercle`, found `Rect`. Box<dyn Surface>efface le type. Chaque valeur part sur le tas, et la case duVecne garde qu'un pointeur gras : 16 octets, contre 8 pour unBox<Cercle>. Toutes les cases ont la même taille, quels que soient les types.Box<dyn Surface>erases the type. Each value goes to the heap, and theVecslot only keeps a fat pointer: 16 bytes, versus 8 for aBox<Cercle>. Every slot has the same size, whatever the types.- Le second mot pointe la vtable du vrai type : sa taille, son alignement, son destructeur et ses méthodes. Les deux
Cerclepointent la même adresse : une table par type, générée à la compilation, pas une par valeur.The second word points to the real type's vtable: its size, alignment, destructor and methods. BothCercles point to the same address: one table per type, generated at compile time, not one per value. - L'appel
f.aire()sur leRect: lire le pointeur de vtable, y lire l'adresse deaire, sauter. Deux lectures et un appel indirect. Le compilateur ne sait pas quelle fonction sera appelée, donc il ne peut pas l'inliner : c'est tout le prix.The callf.aire()on theRect: read the vtable pointer, readaire's address there, jump. Two reads and an indirect call. The compiler doesn't know which function will be called, so it can't inline it: that's the whole price.
Le générique ne mélange pas : E0308
trait Surface { fn aire(&self) -> f64; }
struct Cercle { r: f64 }
struct Rect { l: f64, h: f64 }
fn total<T: Surface>(formes: &[T]) -> f64 { formes.iter().map(|f| f.aire()).sum() }
let formes = vec![Cercle { r: 1.0 }, Rect { l: 2.0, h: 3.0 }];error[E0308]: mismatched types
--> melange.rs:10:42
|
10 | let formes = vec![Cercle { r: 1.0 }, Rect { l: 2.0, h: 3.0 }];
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `Cercle`, found `Rect`Un Vec<T> a un seul T, et une copie de total aussi. Ce n’est pas une lacune. C’est la contrepartie du coût zéro : pour spécialiser le code sur un type, il faut connaître ce type, et on renonce alors à en mélanger plusieurs.
Effacer le type : le pointeur gras
fn total(formes: &[Box<dyn Surface>]) -> f64 { formes.iter().map(|f| f.aire()).sum() }
let formes: Vec<Box<dyn Surface>> = vec![
Box::new(Cercle { r: 1.0 }),
Box::new(Rect { l: 2.0, h: 3.0 }),
Box::new(Cercle { r: 2.0 }),
];
println!("total = {:.2}", total(&formes));
println!("Box<Cercle> : {} octets", size_of::<Box<Cercle>>());
println!("Box<dyn Surface> : {} octets", size_of::<Box<dyn Surface>>());
println!("&dyn Surface : {} octets", size_of::<&dyn Surface>());total = 21.70
Box<Cercle> : 8 octets
Box<dyn Surface> : 16 octets
&dyn Surface : 16 octetstotal n’est plus générique : il n’en existe qu’une copie, qui accepte tout ce qui implémente Surface. Dans le Vec, chaque case est un pointeur gras de deux mots, alors qu’un Box<Cercle> n’en a qu’un. Le premier mot pointe la valeur sur le tas, le second la vtable de son type.
La vtable : une table par type
En séparant les deux mots de chaque pointeur (avec transmute, pour l’observation seulement), on obtient sur une exécution réelle :
donnee 0x1014b9490 vtable 0x100f10090 taille 8 align 8
donnee 0x1014b94f0 vtable 0x100f100b0 taille 16 align 8
donnee 0x1014b9500 vtable 0x100f10090 taille 8 align 8Les deux Cercle partagent la même vtable (…090), le Rect a la sienne (…0b0). Le compilateur génère une vtable par couple (type, trait), une fois pour toutes, et non une par valeur. Elle contient le destructeur, la taille et l’alignement du type (8 et 16 ici), puis l’adresse de chaque méthode. Les adresses changent d’une exécution à l’autre, mais le partage reste. La disposition interne de la vtable n’est pas garantie par le langage ; on la lit ici pour voir, pas pour s’en servir.
le tas Vec<Box<dyn Surface>> vtables (binaire)
┌──────────────┐ ┌────────┬──────────┐ ┌───────────────────┐
│ Cercle r=1.0 │◀───┤ donnée │ vtable ──┼──┬──▶│ Cercle 0x…090 │
└──────────────┘ ├────────┼──────────┤ │ │ drop, 8, 8, aire │
┌──────────────┐ │ │ │ │ └───────────────────┘
│ Rect 2×3 │◀───┤ donnée │ vtable ──┼──┼─┐ ┌───────────────────┐
└──────────────┘ ├────────┼──────────┤ │ └▶│ Rect 0x…0b0 │
┌──────────────┐ │ │ │ │ │ drop, 16, 8, aire │
│ Cercle r=2.0 │◀───┤ donnée │ vtable ──┼──┘ └───────────────────┘
└──────────────┘ └────────┴──────────┘
8 octets + 8 octetsL’appel f.aire() lit le pointeur de vtable, y lit l’adresse de aire, puis saute : deux lectures et un appel indirect, quelques cycles. Le vrai prix est ailleurs. Le compilateur ne sait pas quelle fonction sera appelée, donc il ne peut ni l’inliner ni optimiser au travers. Cela se mesure dans une boucle très chaude qui appelle une petite méthode des millions de fois. Ailleurs, on ne le voit pas : dyn n’est pas « lent », il est « non inlinable ».
Refus 1 : pas de taille sans indirection (E0277)
let formes: Vec<dyn Surface> = Vec::new();error[E0277]: the size for values of type `dyn Surface` cannot be known at compilation time
--> taille.rs:6:17
|
6 | let formes: Vec<dyn Surface> = Vec::new();
| ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Surface`
note: required by an implicit `Sized` bound in `Vec`dyn Surface peut être un Cercle de 8 octets ou un Rect de 16. Un Vec range des cases de taille identique, connue à la compilation. La valeur doit donc vivre ailleurs, et la case ne garde qu’un pointeur gras de taille fixe. C’est pourquoi dyn apparaît toujours derrière quelque chose : Box, &, Rc, Arc.
Refus 2 : ce que la vtable ne peut pas décrire (E0038)
trait Forme {
fn aire(&self) -> f64;
fn dupliquer(&self) -> Self;
}
let f: Box<dyn Forme>;error[E0038]: the trait `Forme` is not dyn compatible
--> forme.rs:7:20
|
7 | let f: Box<dyn Forme>;
| ^^^^^ `Forme` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> forme.rs:3:28
|
1 | trait Forme {
| ----- this trait is not dyn compatible...
2 | fn aire(&self) -> f64;
3 | fn dupliquer(&self) -> Self;
| ^^^^ ...because method `dupliquer` references the `Self` type in its return type
= help: consider moving `dupliquer` to another traitLa note dit l’essentiel : it needs to allow building a vtable. dupliquer rend un Self, donc une valeur du type effacé. L’appelant devrait lui réserver une place sur la pile sans en connaître la taille, et aucune entrée de vtable ne peut décrire ce retour. Les méthodes génériques (fn f<U>(&self, u: U)) sont refusées pour la même raison : il en faudrait une copie par U, en nombre infini. Ce qu’on appelait autrefois object safety s’appelle aujourd’hui dyn compatibility.
Le correctif ne coupe que la méthode fautive :
trait Forme {
fn aire(&self) -> f64;
fn dupliquer(&self) -> Self where Self: Sized;
}
let f: Box<dyn Forme> = Box::new(Cercle { r: 1.0 });
println!("{}", f.aire()); // 3.14where Self: Sized réserve dupliquer aux types concrets, et elle sort de la vtable. Le trait redevient compatible. Si on l’appelle quand même sur f, rustc répond the dupliquer method cannot be invoked on a trait object.
Refus 3 : le 'static qu’on n’a pas écrit
struct Vue<'a> { nom: &'a str }
fn emballer(nom: &str) -> Box<dyn Surface> {
Box::new(Vue { nom })
}error: lifetime may not live long enough
--> statique.rs:6:5
|
5 | fn emballer(nom: &str) -> Box<dyn Surface> {
| - let's call the lifetime of this reference `'1`
6 | Box::new(Vue { nom })
| ^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`
|
help: to declare that the trait object captures data from argument `nom`, you can add an explicit `'_` lifetime bound
|
5 | fn emballer(nom: &str) -> Box<dyn Surface + '_> {
| ++++Effacer le type efface aussi ses emprunts. Sans autre indication, Box<dyn Surface> signifie donc Box<dyn Surface + 'static>, c’est-à-dire « rien d’emprunté ». Une Vue qui emprunte nom ne tient pas cette promesse. On nomme la durée (+ '_, comme le propose rustc), ou on possède la donnée (String au lieu de &str). C’est la règle du 'static en borne, qui revient sans qu’on l’ait écrite.
Ce que l’image cache
- Statique par défaut,
dynsur besoin.fn f(x: &dyn Trait)appelée avec un seul type paie la vtable et perd l’inlining sans rien gagner.dynse justifie pour une collection hétérogène, un plugin ou un type choisi à l’exécution (configuration, entrée). Box<dyn Error>en est un. Le?versBox<dyn Error>et l’anyhow::Errorde l’article sur les erreurs sont des objets traits : n’importe quelle erreur, type effacé, vtable pourDisplayetsource().&dynn’alloue pas. Le pointeur gras ne demande pas deBox.&dyn Surfacepointe une valeur qui vit déjà ailleurs, sur la pile par exemple. Le tas n’est nécessaire que pour posséder la valeur.- Le choix d’un trait se fait à sa conception. Ajouter une méthode qui rend
Selfà un trait public le rend incompatible avecdynet casse tous lesBox<dyn …>des utilisateurs.where Self: Sizedpermet de garder les deux usages.
Pour aller plus loin
- Volume 5, numéro 02 de The Rust Loop, Trait objects : dyn et le dispatch dynamique, qui suit un appel à travers une vtable relevée sur une exécution réelle et détaille trois refus de terrain (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, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369). - The Rust Book : Using Trait Objects
- La référence : dyn compatibility
- Index des erreurs : E0038
The generic doesn’t mix: E0308
trait Surface { fn aire(&self) -> f64; }
struct Cercle { r: f64 }
struct Rect { l: f64, h: f64 }
fn total<T: Surface>(formes: &[T]) -> f64 { formes.iter().map(|f| f.aire()).sum() }
let formes = vec![Cercle { r: 1.0 }, Rect { l: 2.0, h: 3.0 }];error[E0308]: mismatched types
--> melange.rs:10:42
|
10 | let formes = vec![Cercle { r: 1.0 }, Rect { l: 2.0, h: 3.0 }];
| ^^^^^^^^^^^^^^^^^^^^^^^ expected `Cercle`, found `Rect`A Vec<T> has a single T, and so does a copy of total. It isn’t a gap. It’s the flip side of zero cost: to specialise code on a type you must know that type, and you then give up mixing several.
Erasing the type: the fat pointer
fn total(formes: &[Box<dyn Surface>]) -> f64 { formes.iter().map(|f| f.aire()).sum() }
let formes: Vec<Box<dyn Surface>> = vec![
Box::new(Cercle { r: 1.0 }),
Box::new(Rect { l: 2.0, h: 3.0 }),
Box::new(Cercle { r: 2.0 }),
];
println!("total = {:.2}", total(&formes));
println!("Box<Cercle> : {} octets", size_of::<Box<Cercle>>());
println!("Box<dyn Surface> : {} octets", size_of::<Box<dyn Surface>>());
println!("&dyn Surface : {} octets", size_of::<&dyn Surface>());total = 21.70
Box<Cercle> : 8 octets
Box<dyn Surface> : 16 octets
&dyn Surface : 16 octetstotal is no longer generic: only one copy of it exists, accepting anything that implements Surface. In the Vec, each slot is a two-word fat pointer, whereas a Box<Cercle> has only one. The first word points to the value on the heap, the second to its type’s vtable.
The vtable: one table per type
Splitting each pointer’s two words apart (with transmute, for observation only) gives, on a real run:
donnee 0x1014b9490 vtable 0x100f10090 taille 8 align 8
donnee 0x1014b94f0 vtable 0x100f100b0 taille 16 align 8
donnee 0x1014b9500 vtable 0x100f10090 taille 8 align 8Both Cercles share the same vtable (…090), the Rect has its own (…0b0). The compiler generates one vtable per (type, trait) pair, once and for all, not one per value. It holds the type’s destructor, size and alignment (8 and 16 here), then each method’s address. Addresses change from run to run, but the sharing stays. The vtable’s internal layout isn’t guaranteed by the language; we read it here to look, not to rely on it.
the heap Vec<Box<dyn Surface>> vtables (binary)
┌──────────────┐ ┌────────┬──────────┐ ┌───────────────────┐
│ Cercle r=1.0 │◀───┤ data │ vtable ──┼──┬──▶│ Cercle 0x…090 │
└──────────────┘ ├────────┼──────────┤ │ │ drop, 8, 8, aire │
┌──────────────┐ │ │ │ │ └───────────────────┘
│ Rect 2×3 │◀───┤ data │ vtable ──┼──┼─┐ ┌───────────────────┐
└──────────────┘ ├────────┼──────────┤ │ └▶│ Rect 0x…0b0 │
┌──────────────┐ │ │ │ │ │ drop, 16, 8, aire │
│ Cercle r=2.0 │◀───┤ data │ vtable ──┼──┘ └───────────────────┘
└──────────────┘ └────────┴──────────┘
8 bytes + 8 bytesThe call f.aire() reads the vtable pointer, reads aire’s address there, then jumps: two reads and an indirect call, a few cycles. The real price is elsewhere. The compiler doesn’t know which function will be called, so it can neither inline it nor optimise across it. That shows in a very hot loop calling a small method millions of times. Elsewhere, you don’t see it: dyn isn’t “slow”, it’s “non-inlinable”.
Refusal 1: no size without indirection (E0277)
let formes: Vec<dyn Surface> = Vec::new();error[E0277]: the size for values of type `dyn Surface` cannot be known at compilation time
--> taille.rs:6:17
|
6 | let formes: Vec<dyn Surface> = Vec::new();
| ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Surface`
note: required by an implicit `Sized` bound in `Vec`dyn Surface may be an 8-byte Cercle or a 16-byte Rect. A Vec stores slots of identical size, known at compile time. So the value must live elsewhere, and the slot keeps only a fixed-size fat pointer. That’s why dyn always shows up behind something: Box, &, Rc, Arc.
Refusal 2: what the vtable can’t describe (E0038)
trait Forme {
fn aire(&self) -> f64;
fn dupliquer(&self) -> Self;
}
let f: Box<dyn Forme>;error[E0038]: the trait `Forme` is not dyn compatible
--> forme.rs:7:20
|
7 | let f: Box<dyn Forme>;
| ^^^^^ `Forme` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> forme.rs:3:28
|
1 | trait Forme {
| ----- this trait is not dyn compatible...
2 | fn aire(&self) -> f64;
3 | fn dupliquer(&self) -> Self;
| ^^^^ ...because method `dupliquer` references the `Self` type in its return type
= help: consider moving `dupliquer` to another traitThe note says it all: it needs to allow building a vtable. dupliquer returns a Self, so a value of the erased type. The caller would have to reserve stack room for it without knowing its size, and no vtable entry can describe that return. Generic methods (fn f<U>(&self, u: U)) are refused for the same reason: they’d need one copy per U, infinitely many. What used to be called object safety is now called dyn compatibility.
The fix only cuts the offending method:
trait Forme {
fn aire(&self) -> f64;
fn dupliquer(&self) -> Self where Self: Sized;
}
let f: Box<dyn Forme> = Box::new(Cercle { r: 1.0 });
println!("{}", f.aire()); // 3.14where Self: Sized reserves dupliquer for concrete types, and it leaves the vtable. The trait becomes compatible again. If you call it on f anyway, rustc answers the dupliquer method cannot be invoked on a trait object.
Refusal 3: the 'static you didn’t write
struct Vue<'a> { nom: &'a str }
fn emballer(nom: &str) -> Box<dyn Surface> {
Box::new(Vue { nom })
}error: lifetime may not live long enough
--> statique.rs:6:5
|
5 | fn emballer(nom: &str) -> Box<dyn Surface> {
| - let's call the lifetime of this reference `'1`
6 | Box::new(Vue { nom })
| ^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`
|
help: to declare that the trait object captures data from argument `nom`, you can add an explicit `'_` lifetime bound
|
5 | fn emballer(nom: &str) -> Box<dyn Surface + '_> {
| ++++Erasing the type also erases its borrows. Absent any other indication, Box<dyn Surface> therefore means Box<dyn Surface + 'static>, that is “nothing borrowed”. A Vue borrowing nom can’t keep that promise. You name the duration (+ '_, as rustc suggests), or own the data (String instead of &str). It’s the 'static bound rule, coming back without you writing it.
What the picture hides
- Static by default,
dynon need.fn f(x: &dyn Trait)called with a single type pays for the vtable and loses inlining for nothing.dynearns its place for a heterogeneous collection, a plugin, or a type chosen at runtime (configuration, input). Box<dyn Error>is one. The?intoBox<dyn Error>and theanyhow::Errorof the errors article are trait objects: any error, type erased, a vtable forDisplayandsource().&dyndoesn’t allocate. The fat pointer doesn’t need aBox.&dyn Surfacepoints to a value already living elsewhere, on the stack for instance. The heap is only needed to own the value.- A trait’s choice is made when it’s designed. Adding a method returning
Selfto a public trait makes it incompatible withdynand breaks every user’sBox<dyn …>.where Self: Sizedlets you keep both uses.
Going further
- Volume 5, issue 02 of The Rust Loop, Trait objects: dyn and dynamic dispatch, which follows a call through a vtable recorded on a real run and details three field refusals (link at the bottom of the page).
- Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369). - The Rust Book: Using Trait Objects
- The Reference: dyn compatibility
- Error index: E0038