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

后端 未结 3 803
北海茫月
北海茫月 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:05

    We can write a function that temporarily moves out contents of the NotBox and puts something back in before returning it

    That's because you can partially move out from the struct that you take by value. It behaves as if all fields were separate variables. That is not possible though if the struct implements Drop, because drop needs the whole struct to be valid, always (in case of panic).

    As for providing workaround, you haven't provided enough information – especially, why baz needs to take Box as an argument and why quux can't? Which functions are yours and which are part of an API you can't change? What is the real type of Foo? Is it big?

    The best workaround would be not to use Box at all.

提交回复
热议问题