How to Implement the Factory Pattern in Rust

Implement the Factory Pattern in Rust by defining a trait, creating concrete implementations, and using a function to return the appropriate type.

Implement the Factory Pattern in Rust by defining a trait for the product interface, creating concrete structs that implement it, and using a factory function or enum to return the correct type based on input.

trait Product {
    fn do_something(&self);
}

struct ConcreteProductA;
impl Product for ConcreteProductA {
    fn do_something(&self) { println!("A"); }
}

struct ConcreteProductB;
impl Product for ConcreteProductB {
    fn do_something(&self) { println!("B"); }
}

fn factory(type_id: char) -> Box<dyn Product> {
    match type_id {
        'a' => Box::new(ConcreteProductA),
        'b' => Box::new(ConcreteProductB),
        _ => panic!("Unknown type"),
    }
}