I have some non-copyable type and a function that consumes and (maybe) produces it:
type Foo = Vec;
fn quux(_: Foo) -> Option {
So, moving out of a Box
is a special case... now what?
The std::mem
module presents a number of safe functions to move values around, without poking holes (!) into the memory safety of Rust. Of interest here are swap
and replace:
pub fn replace
(dest: &mut T, src: T) -> T
Which we can use like so:
fn baz(mut abox: Box) -> Option> {
let foo = std::mem::replace(&mut *abox, Foo::default());
match quux(foo) {
Some(new_foo) => {
*abox = new_foo;
Some(abox)
}
None => None
}
}
It also helps in the map
case, because it does not borrow the Box
:
fn baz(mut abox: Box) -> Option> {
let foo = std::mem::replace(&mut *abox, Foo::default());
quux(foo).map(|new_foo| { *abox = new_foo; abox })
}