How to implement a trait in Rust which modifies a field of self?

56 Views Asked by At

So how to do this:

pub trait Thing {
    fn do_stuff(&mut self) {
        self.some_field = true;
    }
}

This won't compile because self.some_field is not defined. But the users of this trait would have that field. This would work without a default implementation, but the whole point of the trait is to provide default implementations for certain methods and share functionality that way.

struct Foo {
    some_field: bool
}

// I want this to have a `do_stuff()` method by default.
impl Thing for Foo {}

EDIT: so just to make it clear, is the linked answer the "best practice" solution for the problem?

I mean, having a bunch os similar structs requiring common functionality to be shared among them is a pretty common need. In other languages you would create a common ancestor and make the subclasses inherit these methods. But there is no inheritance in Rust. So is implementing this using a macro (as described in the linked answer) the best solution for this?

0

There are 0 best solutions below