Dispatch statique ou dynamique
Compromis
Dispatch statique ou dynamique est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Learn Rust Coding, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Learn Rust Coding comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Two Ways to Dispatch
When you call a trait method, Rust must decide which concrete implementation runs. There are two strategies: static dispatch (decided at compile time) and dynamic dispatch (decided at runtime).
Static Dispatch With Generics
Generic functions use static dispatch. The compiler generates a specialized copy for each concrete type — a process called monomorphization.
trait Area { fn area(&self) -> f64; }
struct Square { s: f64 }
impl Area for Square { fn area(&self) -> f64 { self.s * self.s } }
fn print_area<T: Area>(shape: &T) {
println!("{}", shape.area());
}
fn main() {
print_area(&Square { s: 4.0 });
}Monomorphization
For each type you call with, the compiler stamps out a dedicated version of the function. The method call becomes a direct call with no lookup, so it is as fast as hand-written code.
Dynamic Dispatch With dyn
Trait objects use dynamic dispatch. One function handles all types; the method address is found at runtime via a vtable.
trait Area { fn area(&self) -> f64; }
struct Square { s: f64 }
impl Area for Square { fn area(&self) -> f64 { self.s * self.s } }
fn print_area(shape: &dyn Area) {
println!("{}", shape.area());
}
fn main() {
print_area(&Square { s: 4.0 });
}The vtable
A trait object is a fat pointer: one part points to the data, the other to a vtable listing the method addresses. Each call indexes into this table.
That extra indirection is the runtime cost.
Speed Trade-off
Static dispatch is faster per call and can be inlined, but generates more machine code. Dynamic dispatch adds a tiny indirection but keeps code size small.
For most apps the difference is negligible; choose based on flexibility.
Code Size Trade-off
Calling a generic function with many types creates many copies, which can bloat the binary. A single dyn function avoids that duplication.
This is why libraries sometimes prefer trait objects internally.
Flexibility Trade-off
Generics force one concrete type per call site, so they cannot hold mixed types in a collection. Trait objects can. If you need a heterogeneous list, dynamic dispatch is the answer.
trait Area { fn area(&self) -> f64; }
struct Square { s: f64 }
struct Rect { w: f64, h: f64 }
impl Area for Square { fn area(&self) -> f64 { self.s * self.s } }
impl Area for Rect { fn area(&self) -> f64 { self.w * self.h } }
fn main() {
let shapes: Vec<Box<dyn Area>> = vec![Box::new(Square { s: 2.0 }), Box::new(Rect { w: 3.0, h: 4.0 })];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{}", total);
}Mixing Both
You can combine them: a generic function might accept impl Trait at the boundary and store values as Box<dyn Trait> internally. Use each where it fits.
A Decision Guide
Quick rules:
- One type per call, hot path? Use generics (static).
- Mixed types in a collection? Use
dyn(dynamic). - Worried about binary size? Lean toward
dyn.
Both Are Zero-Cost Where It Counts
Rust never adds overhead you did not ask for. Generics cost nothing at runtime; trait objects cost only one pointer indirection. You pick the trade-off explicitly.
Quick Check
Test your dispatch knowledge.
Recap
You compared the two dispatch styles:
- Static (generics): monomorphized, fast, larger binary, one type per call
- Dynamic (
dyn): vtable lookup, flexible, smaller code, allows mixed collections - Choose based on flexibility, performance, and binary size needs
Questions Fréquemment Posées
La leçon « Dispatch statique ou dynamique » est-elle gratuite ?
Oui — le texte complet de « Dispatch statique ou dynamique » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Learn Rust Coding, passe à CoddyKit PRO. Le cours Learn Rust Coding comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Dispatch statique ou dynamique » ?
Compromis Tu pratiques Learn Rust Coding avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Learn Rust Coding ?
Aucune expérience préalable n'est requise. Learn Rust Coding sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Dispatch statique ou dynamique » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Learn Rust Coding ?
Oui. Chaque leçon Learn Rust Coding inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Définition de traits
- Objets de traits et dyn
- Dispatch statique ou dynamique
- Méthodes par défaut