expression
Return an owned implementation from a runtime factory
When callers need a uniform interface over heterogeneous implementations, a factory can return an owned trait object. The concrete type remains hidden; allocation and virtual dispatch are trade-offs. Use a simple enum instead if extension through additional implementers is not useful. Both encoders here produce harmless display strings. Expected result (NOT RUN): 2a Common mistake: Returning a reference to a temporary implementation created inside the factory. Static Rust example; not a verified ByteMind executable assessment.
Formal Syntax & Structure
rust syntaxrust
fn create(kind: &str) -> Result<Box<dyn Encoder>, &'static str>Working Example
Example Snippetrust
trait Encoder { fn encode(&self, n: u8) -> String; }struct Decimal;struct Hex;impl Encoder for Decimal { fn encode(&self, n: u8) -> String { format!("{n}") } }impl Encoder for Hex { fn encode(&self, n: u8) -> String { format!("{n:02x}") } }fn create(kind: &str) -> Result<Box<dyn Encoder>, &'static str> { match kind { "decimal" => Ok(Box::new(Decimal)), "hex" => Ok(Box::new(Hex)), _ => Err("unknown encoder") }}fn main() { println!("{}", create("hex").unwrap().encode(42)); }