Trait Objects For Dynamic Dispatch
Store heterogeneous handlers behind Box<dyn Trait> so a registry can dispatch at runtime while each implementation stays a separate type.
Code
trait Handler {
fn name(&self) -> &'static str;
fn handle(&self, input: &str) -> String;
}
struct Upper;
struct Reversed;
impl Handler for Upper {
fn name(&self) -> &'static str {
"upper"
}
fn handle(&self, input: &str) -> String {
input.to_uppercase()
}
}
impl Handler for Reversed {
fn name(&self) -> &'static str {
"reversed"
}
fn handle(&self, input: &str) -> String {
input.chars().rev().collect()
}
}
fn main() {
// 异构集合:不同具体类型统一进 Vec<Box<dyn Handler>>
let handlers: Vec<Box<dyn Handler>> = vec![Box::new(Upper), Box::new(Reversed)];
for handler in &handlers {
println!("{}: {}", handler.name(), handler.handle("rust"));
}
// 按名字选择:运行时决定走哪个实现
let name = "reversed";
if let Some(found) = handlers.iter().find(|h| h.name() == name) {
println!("dispatched: {}", found.handle("dispatch"));
}
}What the code does
Count the functions name, handle and main as the entire surface area of Trait Objects For Dynamic Dispatch.
The one repetition in this snippet is the loop for handler in &handlers.
Applying it
The main signature reads fn name(&self) -> &'static str;
Output lines are prefixed (dispatched:), making each step’s effect easy to spot.
Start the program and main runs name and handle one after another.
Statements that matter
let handlers: Vec<Box<dyn Handler>> = vec![Box::new(Upper), Box::new(Reversed)];
if let Some(found) = handlers.iter().find(|h| h.name() == name) {
println!("dispatched: {}", found.handle("dispatch"));
}
fn handle(&self, input: &str) -> String {
input.to_uppercase()
}
Interactive Tools for This Topic
FAQ
- What does Trait Objects For Dynamic Dispatch print when run?
- Execute the whole file; each printed line is prefixed with a label like `dispatched:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.