Delegate inexistent methods (and maybe fields) to a specific method of a trait

This is a proposal to support a #[trait_common] attribute for a trait instance method:

trait T {
    #[trait_common]
    fn common(&self) -> Arc<Common>;
}

struct Common {
}

impl Common {
    fn f(&self) {
    }
}

What does this do? It does this:

trait T {
    fn common(&self) -> Arc<Common>;

    fn f(&self) {
        self.common().f();
    }
}

This allows a trait to share a common implementation with multiple implementors by providing accessors for all of the common fields and methods.

I didn't show an example showing how fields are delegated to. I'm not sure if allowing to access fields from self.common() is as trivial as accessing methods. Implementing just inexistent methods should be easier from compiler architecture.

I have absolutely no idea what you're trying to show here.

1 Like

They want to tag a getter method and have all the inherent methods of the struct [1] automatically uplifted to trait methods that call the getter and then the inherent method.

I.e. some sort of fields-in-traits mechanism.


  1. after unwrapping layers like Arc ↩ī¸Ž

1 Like

This is entirely possible via proc macros.

2 Likes

Here is a crate

This isn't much what I'm looking for. I don't want to delegate to a trait; I want to delegate from a trait to one of its methods.