Statischer vs. dynamischer Dispatch
Abwägungen
Statischer vs. dynamischer Dispatch ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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
Häufig gestellte Fragen
Ist die Lektion „Statischer vs. dynamischer Dispatch“ kostenlos?
Ja — der vollständige Text von „Statischer vs. dynamischer Dispatch“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Statischer vs. dynamischer Dispatch“?
Abwägungen Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Learn Rust Coding zu starten?
Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „Statischer vs. dynamischer Dispatch“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?
Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Traits definieren
- Trait-Objekte und dyn
- Statischer vs. dynamischer Dispatch
- Standardmethoden