Get reference to field inside 'newtype' struct?


#1

Suppose I have a single-field tuple struct, like so:

    struct Ps(Vec<u32>);

I want to implement a method that needs a reference to the Vec<u32> inside Ps, however I don’t know how to do this.
So far I’ve tried like this:

    impl Ps {
        fn get_vec(&self) -> &Vec<u32> {
            match *self {
                Ps(x) => &x    
            }
        }
    }

However x doesn’t live long enough, it dies at the end of the match expression.
I feel like I’m missing something; surely there’s an easier way to do this?


#2

What you’re doing won’t work because the x in your pattern is bound only for the scope of the match expression. You want to refer to the inner field directly, like this:

    impl Ps {
        fn get_vec(&self) -> &Vec<u32> {
            &self.0
        }
    }

#3

Thank you so much.


#4

While &self.0 is simpler, it’s also useful to know how to bind a reference in a match:

struct Ps(Vec<u32>);
impl Ps {
    fn get_vec(&self) -> &Vec<u32> {
        match *self {
            Ps(ref x) => x    
        }
    }
}

#5

Similarly, this also works instead of match:

fn get_vec(&self) -> &Vec<u32> {
    let Ps(ref x) = *self;
    x
}