Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two structures inherit one trait, but with extra parameters

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 {}
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading