Since Rust
does not support inheritance, we cannot reuse the states of another struct
.
Take an example in Head First Design Patterns, an abstract Duck
class has an attribute FlyBehavior
, and it also provides getter
and setter
.
abstract class Duck {
private FlyBehavior flyBehavior;
public void setFlyBehavior(FlyBehavior flyBehavior) { this.flyBehavior = flyBehavior; }
public FlyBehavior getFlyBehavior() { return this.flyBehavior; }
}
But, in Rust, we are not able to write the default implementation for reuse.
trait Duck {
fn get_fly_behavior(&self) -> &dyn FlyBehavior;
fn set_fly_behavior(&mut self, fly_behavior: Box<dyn FlyBehavior>);
}
And any struct implementing Duck
has to write the same getter
and setter
. So, is there any idiomatic way to reuse the implementations of getter
and setter
in Rust?