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
?