How do I make two structures inherit one trait, but with extra parameters?
And I heard that doing so in Rust is not recommended. Why?
struct Foo {name: String,}
struct FooPlus {name: String, lvl: i128,}
trait Trait {
fn show(&self);
fn new(name: &str) -> Self;
// fn new(name: &str, lvl: i128) -> Self;
}
impl Trait for Foo {
fn new(name: &str) -> Self {}
fn show(&self) {}
}
impl Trait for FooPlus {
fn show(&self) {}
fn new(name: &str, lvl: i128) -> Self {}
}
>Solution :
You can make the extra parameter be an associated type to the trait.
trait Trait {
type ConstructParam
fn show(&self);
fn new(name: &str, arg: ConstructParam) -> Self;
}
impl Trait for Foo {
type ConstructParam = ();
fn show(&self) { ... }
fn new(name: &str, arg: ()) -> Self { ... }
}
impl Trait for FooPlus {
type ConstructParam = i128;
fn show(&self) { ... }
fn new(name: &str, arg: i128) -> Self { ... }
}
Note that you have to call the "no-argument" constructor with an extra unit argument, so Foo::new("example name", ()), but that unit argument is zero-sized and thus will almost certainly be optimized to nothing.
Though, as already mentioned in the comments, having new in a trait is odd. How often are you going to polymorphically call new on a type that’s generic? If you really need to polymorphically generate instances, that sounds like an application of the factory pattern, not a good use for traits in this way. And if you’re not doing it polymorphically, then just make new part of the impl for Foo and FooPlus separately.