How to write a guard that allows destructuring?

⚓ Rust    📅 2025-11-27    👤 surdeus    👁️ 6      

surdeus

Given

pub struct WriteGuard<'a, T> {
  entry: &'a mut T
}

impl<'a, T> Drop for WriteGuard<'a, T>,
{
  fn drop(&mut self) {
    self.entry.after_change()
  }
}

I'd like to write a function that extracts an immutable reference:

impl<'a, T> WriteGuard<'a, T> {
  pub fn into_ref(self) -> &T {
    ????
  }
}

I'm fine with the destructor running or not running automatically, since I can run the same operation within into_ref().

Things I tried:

  • &*ManuallyDrop::new(self).entry, returns reference to a temporary value
  • let WriteGuard { entry } = self, cannot move out of type which implements the Drop trait

Is there no way around unsafe and pointer casting in this case?

1 post - 1 participant

Read full topic

🏷️ Rust_feed