How can I reuse a box that I have moved the value out of?

后端 未结 3 790
北海茫月
北海茫月 2021-01-11 18:26

I have some non-copyable type and a function that consumes and (maybe) produces it:

type Foo = Vec;

fn quux(_: Foo) -> Option {
             


        
3条回答
  •  时光说笑
    2021-01-11 19:10

    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 })
    }
    

提交回复
热议问题