Implementing `Deref` on a struct where `Target` is Self with dereferenced fields

Here's what I'm trying to achieve:

// I wish to dereference this into any GenericFields<U> where T: Deref<Target = U>.
struct GenericFields<T> {
    a: T,
    b: T,
    c: T,
}

impl<T: Deref> Deref for GenericFields<T>
where
    <T as Deref>::Target: Sized,
{
    type Target = GenericFields<<T as Deref>::Target>;

    fn deref(&self) -> &Self::Target {
        todo!()
    }
}

Unfortuantly I can't figure out if this is possible. Is it both possible, and if so, how can i achieve it?

Here's a longer example to give context if needed:

struct IntegerWrapper(i32);

impl Deref for IntegerWrapper {
    type Target = i32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

// I wish to call the methods of `GenericFields<i32>` on this struct.
struct WrapperFields(GenericFields<IntegerWrapper>);

// I am having trouble with this implementation:
impl Deref for WrapperFields {
    type Target = GenericFields<i32>;

    fn deref(&self) -> &Self::Target {
        // I believe this implementation requires that of the prior example.
        todo!()
    }
}

Thank you for any guidance.

1 Like

In this particular case I would've used zerocopy to safely transmute &GenericWrapper<IntegerWrapper> to &GenericWrapper<i32>.

In more general case, you need to return a valid reference to some type that doesn't exist. The only way I see is to have a RefCell<SomeLinkedList<Box<dyn Any>>>, in deref create a new element with required layout and push it, return a reference to it. When any &mut access happens, clear the whole thing - you are guaranteed that if &mut present, nobody has & anymore, thus that memory is not used anymore.

Thanks for the response. I followed what you said, but used bytemuck instead with cast_ref as that was already a dependency in my project. That did the trick.