Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a variante of take() that allows returning values #13

Open
nosewings opened this issue Dec 31, 2021 · 0 comments
Open

Add a variante of take() that allows returning values #13

nosewings opened this issue Dec 31, 2021 · 0 comments

Comments

@nosewings
Copy link

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
   }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant