New type idiom: forward fields

When using the new type idiom, is it possible to "forward" the fields ?

struct Inner {
    x: u32,
    y: u32
}

struct Outer(Inner);

impl Outer {
    pub fn new(x: u32, y: u32) -> Self {
        Self(Inner{x, y})
    }
}

fn main() {
    let foo = Outer::new(5, 7);
    let x = foo.x;
    let y = foo.y;
    
    println!("{}, {}", x, y);
}

It will work with Deref as long as the inner fields are visible to the caller:

impl std::ops::Deref for Outer {
    type Target = Inner;
    
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

(But that's not really what Deref is intended for...)

3 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.