Dynamic Dispatch With Trait Objects
Store heterogeneous implementations behind a Box dyn trait to select behaviour at runtime, trading monomorphisation for flexibility.
Code
trait Exporter {
fn name(&self) -> &str;
fn export(&self, rows: &[String]) -> String;
}
struct CsvExporter;
struct JsonExporter;
impl Exporter for CsvExporter {
fn name(&self) -> &str {
"csv"
}
fn export(&self, rows: &[String]) -> String {
rows.join("\n")
}
}
impl Exporter for JsonExporter {
fn name(&self) -> &str {
"json"
}
fn export(&self, rows: &[String]) -> String {
let items: Vec<String> = rows.iter().map(|r| format!("\"{r}\"")).collect();
format!("[{}]", items.join(","))
}
}
fn select(name: &str) -> Option<Box<dyn Exporter>> {
match name {
"csv" => Some(Box::new(CsvExporter)),
"json" => Some(Box::new(JsonExporter)),
_ => None,
}
}How it works
Dynamic Dispatch With Trait Objects keeps everything in the functions name, export and select.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Using it
The main signature reads fn name(&self) -> &str;
name is reached through its receiver type Exporter — call it on a value of that type rather than importing the name.
Key statements
let items: Vec<String> = rows.iter().map(|r| format!("\"{r}\"")).collect();
fn select(name: &str) -> Option<Box<dyn Exporter>> {
match name {
"csv" => Some(Box::new(CsvExporter)),
"json" => Some(Box::new(JsonExporter)),
_ => None,
}
}
fn export(&self, rows: &[String]) -> String {
rows.join("\n")
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `name`, `export`, `select` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.