How to extend a trait-implementing struct, while keeping the trait implementation in the extending struct?

I am currently trying to find out if it is possible (or if it even makes sense) to extend a rather complex existing struct with metadata, while keeping the trait implementations of the wrapped struct, so that the extended struct may be used in place of the original one:

#[derive(Debug)]
struct Internal<T> {
    some_thing_internal: T
}

trait SomeTrait: std::fmt::Debug {
    type InternalType: std::fmt::Debug;
    
    fn always_true(i: Self::InternalType) -> bool;
}

#[derive(Debug)]
struct Original {
    value: u64
}

impl SomeTrait for Original {
    type InternalType = Internal<u64>;
    
    fn always_true(_i: Self::InternalType) -> bool {
        true
    }
}

Say we have this struct Original wrapping a single u64 value, I then implement a set of rather complex traits, like SomeTrait, for this struct, also including associated types like InternalType which are also bound by other complex traits, Debug in this example.

My approach would be to create a wrapping struct like:

struct ExtendedOriginal {
  orig: Original,
  metadata: u64,
}

Then I would like to use this extended struct ExtendedOriginal in place of the original struct Original, so the extended one also would need to satisfy the SomeTrait bound.
To avoid having to re-implement all required associated types and functions for ExtendedOriginal, I'd like to somehow delegate everything concerning the trait SomeTrait to the field original in ExtendedOriginal.

Is this possible or is there a better approach to this?

There isn't currently a way to declare delegating a trait impl to a struct's field. Though it's been under discussion for the better part of the last decade.

RFC
Closing comment

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.