Quicker way to reborrow a enum which acts like a mutable reference?

I have a enum A which acts like a mutable reference. I need to reborrow it frequently. So I wander whether there is a quicker implementation? I think the matching stuff is unneccessary, and I guess we can unsafely copy it, am I right?

enum A<'a> {
    B,
    C(&'a mut bool),
}

impl<'a> A<'a> {
    fn reborrow<'b>(&'a mut self) -> A<'b> where 'a:'b {
        match self {
            A::B => A::B,
            A::C(b) => A::C(&mut *b),
        }
    }
}

Unsafely copying it would be UB (two active &mut to the same thing).

Have you actually observed an impact on --release? All the matching stuff compiles away in this case. Maybe slap an #[inline] on the method.

And why do you have an &'a mut A<'a>? If you get ahold of one of those, the referenced A<'a> is no longer directly usable, so you might as well just use the A<'a> (which is already covariant in 'a, and can thus also be used as A<'b>).

6 Likes

Yes, it should be &'b mut self. I have guessed that the matching stuff will be optimized away, but I didn't confirm it. Thank you for your explaination!

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.