I have Java background and i'm playing with Rust. Here is the conceptual challenge that i know how to solve in Java, but not in Rust at the moment.
I have a product trait and concrete product impl hierarchy. In the tests i need to init it depending on the concrete class. In java i'd just check the class, cast to it and init it as needed. This is how i try to solve it in Rust (and it expectedly fails):
pub trait TProduct {
fn something();
}
pub trait TProductFactory {
fn build() -> Box<dyn TProduct>;
}
pub TProduct for ProductType1 {}
pub TProduct for ProductType2 {}
pub TProduct for ProductType3 {}
// in the tests:
let product = factory.build();
// pseudo-code below ---
// if product is ProductType1 {
(product as ProductType1).setTitle("title1"); // specific init 1
}
// else if product is ProductType2 ... {
(product as ProductType1).setTitle("title2"); // specific init 2
//}
// ^ How can i have concrete-specific behaviour (eg. init here) ---
//
In regular conditions (production code) i'd subclass or wrap to have concrete-specific behaviour, but structs can't be extended in Rust. What is the canonical Rust way to achieve it?
PS. I consider having another factory impl or wrapper just to have specific behaviour for the test as an over-kill.