How to take ownership of a field of uniquely borrowed struct?

I have got structure like this, where Foo is not copiable, or clonable (at least cheaply) in my case.:

struct Foo {
    field: String
}

struct Bar {
    field: Option<Foo>
}

Next, I have got a variable of &mut Bar type. I would like to set it's field to None, and take ownership of the variable to pass it to other call. Something like this (but it does not compile due to cannot move out of borrowed content):

let bar_mut: &mut Bar = ...;
let field_value_ownership_would_be_taken = bar_mut.field;
bar_mut.field = None;
call_some_other_function_which_requires_move_of_its_argument(field_value_ownership_would_be_taken);

How could I achieve it in rust?

1 Like

Option::take() is what you’re after

1 Like

Great, I google for this like option swap :slight_smile: but missed this one. If it was not Option (but was only T) would mem:replace be a standard pattern to do this?

Yes, that's what take does internally.

Yup (Option::take() uses replace internally).