3 ms·
They’re not functionally equivalent for one reason: `panic` unwinding. Rust can catch panics, and if you catch a panic while calling the latter, you will effect
by armchairhacker 3y ago
They’re not functionally equivalent for one reason: `panic` unwinding. Rust can catch panics, and if you catch a panic while calling the latter, you will effectively drop `T`.
Otherwise, if you have a temporary value (e.g. `Default`), you can convert the former to the latter via `std::mem::replace` or `std::mem::take` (which replaces with default)
fn f1(x: &mut T) {
let y = std::mem::take(x);
*x = f2(y);
}
and you can always convert the latter to the former
fn f2(mut x: T) -> T {
f1(&mut x);
return x;
}
See also the `replace_with` crate: https://docs.rs/replace_with https://docs.rs/replace_with
- tialaramex 3y agoThis seems like it's just re-stating what I said? I guess it can be tidier to use replace rather than swap depending on the circumstances. Edited-to-add: The replace_with crate seems like it's taking the opposite approach to Aria's "Pre-pooping your pants" essay and I don't like that. It has a bunch of safety pre-requisites on functions labelled safe, which is not good Rust.