Is there a function like swap that returns the original value?

I noticed that I used this pattern quite a lot this morning:

let mut has_fused = false;
let fuse = move |some_value| {
    let was_fused = has_fused;
    has_fused = foo(some_value);

This is relatively verbose, and could be nicely be abstracted:

// sorry for the naming, I don't have anything better than `reference`
fn get_and_assign<T>(reference: &mut T, new_value: T) -> T {
    let mut new_value = new_value;
    swap(reference, &mut new_value);

let mut has_fused = false;
bar(|some_value| get_and_assign(&mut has_fused, foo(some_value));

Is there a similar function to get_and_assign in std?


1 Like

Perfect, thanks!

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.