« the trait is not dyn compatible » : dyn Trait et la vtable en Rust, le modèle mental (E0038) "the trait is not dyn compatible": dyn Trait and the vtable in Rust, the mental model (E0038)

Un générique a un seul type par copie ; pour mélanger des types, Box<dyn Trait> efface le type. La case devient un pointeur gras de 16 octets, un mot vers la valeur, un vers la vtable de son type. Puis les trois refus : taille inconnue (E0277), Self dans la vtable (E0038), 'static implicite. Animation et sorties réelles de rustc.A generic has a single type per copy; to mix types, Box<dyn Trait> erases the type. The slot becomes a 16-byte fat pointer, one word to the value, one to its type's vtable. Then the three refusals: unknown size (E0277), Self in the vtable (E0038), implicit 'static. Animation and real rustc output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
TraitsTraits
PubliéPublished

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 Trait est 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 Trait is 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 pointeur, deux motsOne pointer, two wordsdonnées + vtable, résolu à l'exécutiondata + vtable, resolved at run timeles valeurs (tas)the values (heap)le Vec<Cercle>the Vec<Cercle>les vtables (binaire)the vtables (binary)Cercle { r: 1.0 }Cercle { r: 1.0 }Rect { 2.0, 3.0 }Rect { 2.0, 3.0 }✕Cercle { r: 2.0 }Cercle { r: 2.0 }Cercle0x…090drop_in_placetaille 8 · align 8aire → Cercle::aireRect0x…0b0drop_in_placetaille 16 · align 8aire → Rect::aireE0308 · mismatched types : expected `Cercle`, found `Rect`E0308 · mismatched types: expected `Cercle`, found `Rect`vérifié avec rustc 1.100checked with rustc 1.100
  1. 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`.
  2. Box<dyn Surface> efface le type. Chaque valeur part sur le tas, et la case du Vec ne garde qu'un pointeur gras : 16 octets, contre 8 pour un Box<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 the Vec slot only keeps a fat pointer: 16 bytes, versus 8 for a Box<Cercle>. Every slot has the same size, whatever the types.
  3. Le second mot pointe la vtable du vrai type : sa taille, son alignement, son destructeur et ses méthodes. Les deux Cercle pointent 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. Both Cercles point to the same address: one table per type, generated at compile time, not one per value.
  4. L'appel f.aire() sur le Rect : lire le pointeur de vtable, y lire l'adresse de aire, 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 call f.aire() on the Rect: read the vtable pointer, read aire'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.
Dispatch dynamique en Rust : Box<dyn Surface> est un pointeur gras de 16 octets, un mot vers la valeur et un vers la vtable de son type. Une vtable par type, et l'appel la traverse à l'exécution.Dynamic dispatch in Rust: Box<dyn Surface> is a 16-byte fat pointer, one word to the value and one to its type's vtable. One vtable per type, and the call goes through it at runtime.

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 octets

total 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 8

Les 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 octets

L’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 trait

La 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.14

where 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, dyn sur besoin. fn f(x: &dyn Trait) appelée avec un seul type paie la vtable et perd l’inlining sans rien gagner. dyn se 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 ? vers Box<dyn Error> et l’anyhow::Error de l’article sur les erreurs sont des objets traits : n’importe quelle erreur, type effacé, vtable pour Display et source().
  • &dyn n’alloue pas. Le pointeur gras ne demande pas de Box. &dyn Surface pointe 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 avec dyn et casse tous les Box<dyn …> des utilisateurs. where Self: Sized permet de garder les deux usages.

Pour aller plus loin

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 octets

total 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 8

Both 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 bytes

The 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 trait

The 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.14

where 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, dyn on need. fn f(x: &dyn Trait) called with a single type pays for the vtable and loses inlining for nothing. dyn earns its place for a heterogeneous collection, a plugin, or a type chosen at runtime (configuration, input).
  • Box<dyn Error> is one. The ? into Box<dyn Error> and the anyhow::Error of the errors article are trait objects: any error, type erased, a vtable for Display and source().
  • &dyn doesn’t allocate. The fat pointer doesn’t need a Box. &dyn Surface points 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 Self to a public trait makes it incompatible with dyn and breaks every user’s Box<dyn …>. where Self: Sized lets you keep both uses.

Going further

Questions fréquentesFrequently asked questions

Que signifie « the trait is not dyn compatible » (E0038) ?What does "the trait is not dyn compatible" (E0038) mean?

Un trait ne peut servir derrière dyn que si on peut lui construire une vtable. Une méthode qui rend Self (ou qui est générique) empêche cela : derrière dyn, le type est effacé, et l'appelant ne saurait pas quelle place réserver au retour. rustc nomme la méthode fautive. Correctifs : ajouter where Self: Sized à cette méthode pour la sortir de la vtable, ou la déplacer dans un autre trait.A trait can only be used behind dyn if a vtable can be built for it. A method returning Self (or a generic method) prevents that: behind dyn, the type is erased, and the caller wouldn't know how much room to reserve for the return. rustc names the offending method. Fixes: add where Self: Sized to that method to take it out of the vtable, or move it to another trait.

Pourquoi « the size for values of type `dyn Trait` cannot be known at compilation time » (E0277) ?Why "the size for values of type `dyn Trait` cannot be known at compilation time" (E0277)?

dyn Trait désigne une valeur de n'importe quel type qui implémente le trait, et ces types n'ont pas la même taille (un Cercle de 8 octets, un Rect de 16). Un Vec, une variable ou un argument exigent une taille connue à la compilation. Il faut une indirection : Box<dyn Trait>, &dyn Trait ou Rc<dyn Trait>, qui ont tous une taille fixe.dyn Trait means a value of any type implementing the trait, and those types don't have the same size (an 8-byte Cercle, a 16-byte Rect). A Vec, a variable or an argument require a size known at compile time. You need an indirection: Box<dyn Trait>, &dyn Trait or Rc<dyn Trait>, all of fixed size.

Qu'est-ce qu'un pointeur gras et une vtable en Rust ?What are a fat pointer and a vtable in Rust?

Box<dyn Surface> fait 16 octets sur une machine 64 bits, contre 8 pour Box<Cercle> : un mot pointe la valeur, l'autre la vtable de son type. La vtable contient le destructeur, la taille, l'alignement et l'adresse de chaque méthode. Il y en a une par type, générée à la compilation : deux Cercle pointent la même adresse de vtable.Box<dyn Surface> is 16 bytes on a 64-bit machine, versus 8 for Box<Cercle>: one word points to the value, the other to its type's vtable. The vtable holds the destructor, size, alignment and each method's address. There's one per type, generated at compile time: two Cercle point to the same vtable address.

dyn Trait est-il lent ?Is dyn Trait slow?

L'appel coûte deux lectures mémoire et un saut indirect, quelques cycles. Le vrai coût est ailleurs : le compilateur ne sait pas quelle fonction sera appelée, donc il ne peut pas l'inliner ni optimiser à travers. Ça ne se mesure que dans une boucle très chaude appelant une petite méthode. Ailleurs, c'est invisible.The call costs two memory reads and an indirect jump, a few cycles. The real cost is elsewhere: the compiler doesn't know which function will be called, so it can't inline it or optimise across it. It only shows in a very hot loop calling a small method. Elsewhere, it's invisible.

Pourquoi Box<dyn Trait> exige-t-il 'static ?Why does Box<dyn Trait> require 'static?

Effacer le type efface aussi ses emprunts. Sans précision, Box<dyn Trait> veut dire Box<dyn Trait + 'static> : la valeur ne contient aucun emprunt. Une valeur qui emprunte un argument viole cette promesse, d'où « lifetime may not live long enough ». Le correctif, proposé par rustc, est de nommer la durée : Box<dyn Trait + '_>.Erasing the type also erases its borrows. Unless stated, Box<dyn Trait> means Box<dyn Trait + 'static>: the value holds no borrow. A value borrowing an argument breaks that promise, hence "lifetime may not live long enough". The fix, suggested by rustc, is to name the duration: Box<dyn Trait + '_>.

RustTraitsdynVtableE0038Modèle mental

← Tous les articlesAll articles