`Deref` and `DerefMut` derive macros

Hello! I've been working with Rust for the past couple of months. One thing I've seen many times in our codebase is something like the following:

struct MyStruct(SomeType);
// ...
my_struct.0.my_method();

For that I've implemented some Deref and DerefMut from time to time. Why isn't there a derive macro for that? It could be useful to expose the wrapped type interface whilst extending more functionality. Is there anything I'm completely missing here?

#[derive(deref(0))]
struct MyStruct(SomeType);
// ...
my_struct.my_method();

// Or acessing a field
#[derive(deref(inner_field))]
struct MyStruct{
    inner_field: SomeType,
    other_field: OtherType,
};
// ...
my_struct.my_method();

derive_more has a Deref derive macro.

3 Likes

Where and when Deref[Mut] should be implemented has been a somewhat controversial issue historically. Originally the traits (and the mechanism of deref coercion) were designed specifically for dereferencing pointer-like types, not for being a general-purpose tool for delegating to a field. The current documentation appears to be more open to the delegation use case than what I remembered, but there are still a lot of "terms and conditions" involved.

4 Likes