Rust: how to reuse the implementations of getter and setter?

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?

If the problem is described in full generality like this, then no. You could write a macro that generates the impl Duck for MyStruct block for you, but I doesn't quite sound like that's what you wanted.

If you are more specific about your use-case, then I can give more specific advice.