0

I have two structs A and B that are similar and have overlapping behaviour. I defined a trait which both of the structs implement.

Both structs have the same field a and the method is(&self) defined in the trait has the exact same implementation in both struct, so I wanted to move the implementation to the trait, instead of having duplicate code in both structs.

However, the is(&self) method needs to access field a of &self for the calculation of the return value.

Here some example code of the problem:

trait T {
    fn is(&self) -> bool;
    // other methods
}

pub struct A {
    a: i32,
}

impl T for A {
    fn is(&self) -> bool {
        // This calculation is actually more complex
        self.a > 0
    }
    // other methods of T
}

pub struct B {
    a: i32,
    // more fields
}

impl T for B {
    fn is(&self) -> bool {
        // This calculation is actually more complex
        self.a > 0
    }
    // other methods of T, that are implemented differently from A's implementations
}

How can I implement the is(&self) method once for struct A and B without defining methods in the trait to access the field a?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
David
  • 1,672
  • 2
  • 13
  • 32
  • You cannot. I believe this to be already answered by [Implementing a trait for multiple types at once](https://stackoverflow.com/q/39150216/155423). If you disagree, please [edit] your question to explain the exact differences. – Shepmaster Apr 07 '18 at 21:09
  • I agree. Didn't find that question, here. Sorry for the duplicate and thank you for the comment. – David Apr 07 '18 at 21:11
  • There's no need to apologize for duplicates! Each duplicate leaves a signpost back to another question. Now this question will help people who phrased the question in the same way you did to find the right answer! – Shepmaster Apr 07 '18 at 21:13
  • Maybe you could have each implement `trait HasA { fn getA(&mut self) -> &mut i32; }`, then implement `impl T { fn is(&mut self); }`. It's not quite the same thing but the logical structure is something like what you want. – NovaDenizen Apr 08 '18 at 03:37

0 Answers0