Emulate interfaces/inheritence to remove duplicate functions


#1

Hi all. I have this common behaviors for products but Rust won’t let me access fields in&self. Other than blindly copy-pasting duplicate functions, how can I work around this? Note that later in the project I will have multiple kinds of hardware and many of them; same goes for software. I do not want to copy-paste anything.

struct Manufacturer<'a>
{
    name: &'a str
}

struct Date<'a>
{
    //YYYYMMDD
    value: &'a [u8; 8]
}

trait product
{
    fn get_manufacturer<'a>(&self) -> Manufacturer<'a>
    {
        self.manufacturer
    }
    fn get_release_date<'a>(&self) -> Date<'a>
    {
        self.release_date
    }
    fn get_model<'a>(&self) -> &'a str
    {
        self.model
    }
}


struct Hardware<'a>
{
    manufacturer: Manufacturer<'a>,
    release_date: Date<'a>,
    model: &'a str
}

impl <'a> product for Hardware<'a>
{
}

struct Software<'a>
{
    manufacturer: Manufacturer<'a>,
    release_date: Date<'a>,
    model: &'a str
}

impl <'a> product for Software<'a>
{
}

struct System<'a>
{
    hardarray: Vec<Hardware<'a>>,
    softarray: Vec<Software<'a>>
}

fn main()
{
}

#2

You can’t have fields in traits. There’s been some discussion and proposal(s) for adding them, but that’s for the future.

For now, your best bet is likely to employ macros. Here’s a quick example with (more or less) your code: play


#3

You can emulate single inheritance with AsRef Deref, like String/str does.

pub struct Child {
    common: Common,
}

impl AsRef<Common> for Child {
  fn as_ref(&self) -> &Common {
    &self.common
  }
}

and &child will work where &Common is expected.

BTW: it’s super extra weird to have a struct Date that instead of owning the date value, it holds a temporary reference to another struct that actually is the date value. You probably want owned values and never use & in any of your structs.


#4

You’re probably referring to deref coercion, which requires a Deref<Target=Common> impl. Note that this type of “inheritance emulation” is considered somewhat of an anti-pattern.