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

⚓ Rust    📅 2025-10-26    👤 surdeus    👁️ 4      

surdeus

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.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed