How to avoid impl repetition in Rust?

Viewed 279

I have the following implementation, but I don't want to repeat myself. How can I use a implementation that have the same body on different structs without repeating?

impl Message for CreateHero {
    type Result = Result<Hero, Error>;
}

impl Message for SearchHero {
    type Result = Result<Hero, Error>;
}

impl Message for DeleteHero {
    type Result = Result<Hero, Error>;
}
1 Answers

The answer to how to avoid repetition in Rust is usually macros.

Your case is actually quite simple, as macros go:

macro_rules! hero_message {
    ($name : ident) => {
        impl Message for $name {
            type Result = Result<Hero, Error>;
        }
    }
}
hero_message!{CreateHero}
hero_message!{SearchHero}
hero_message!{DeleteHero}

Reading the answer in the linked duplicated question, you can also write a generic trait implementation, that for simple problems like yours, would look more idiomatic. It would look like this:

trait MessageHero {}

impl<T: MessageHero> Message for T {
    type Result = Result<Hero, Error>;
}

impl MessageHero for CreateHero {}
impl MessageHero for SearchHero {}
impl MessageHero for DeleteHero {}
Related