take_mut icon indicating copy to clipboard operation
take_mut copied to clipboard

Add a variante of take() that allows returning values

Open nosewings opened this issue 3 years ago • 0 comments

In keeping with Rust's expression-oriented nature, it would be nice to have a variant of take() that allows returning some value from the closure. A sort of linear state monad.

Something like this:

pub fn take_return<T, R, F>(mut_ref: &mut T, closure: F) -> R
here
   F: FnOnce(T) -> (R, T),

   unsafe {
       let old_t = std::ptr::read(mut_ref);
       let (r, new_t) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| closure(old_t)))
           .unwrap_or_else(|_| std::process::abort());
       std::ptr::write(mut_ref, new_t);
       r
   }

nosewings avatar Dec 31 '21 11:12 nosewings