Code Example Template
Deep-Dive System Documentation
Custom Traits: Modular Interfaces
A Custom Trait defines a collection of methods that types can implement to support dynamic extension systems.
Designing Plugin Actions
In macro utilities, plugins implement a shared interface to run commands uniformly:
pub struct PluginError;
trait ExecutableAction {
fn execute(&self) -> Result<(), PluginError>;
}
struct ShellMacro {
command: String,
}
impl ExecutableAction for ShellMacro {
fn execute(&self) -> Result<(), PluginError> {
println!("Running: {}", self.command);
Ok(())
}
}
Dispatch Types: Static vs Dynamic
When consuming traits, Rust supports two modes of execution:
- Static Dispatch (
impl Trait): The compiler monomorphizes code. Fast, direct inline calls.fn run_static(action: impl ExecutableAction) { let _ = action.execute(); } - Dynamic Dispatch (
dyn Trait): The compiler uses a vtable (virtual method table) pointer. This allows heterogeneous collections but adds a minor pointer indirection lookup cost.fn run_dynamic(actions: Vec<Box<dyn ExecutableAction>>) { for act in actions { let _ = act.execute(); } }
Quick Reference Guide
trait Run { fn run(&self); }
impl Run for App { fn run(&self) {} }