Moving out from Cow

Is there a way to move out (for Cow::Owned) from Cow?

I'm not really sure what you mean. You can use Cow::into_owned or Cow::to_mut to extract owned data from a Cow, or you can use mem::take to take the value out of a Cow leaving a default value in its place.

I mean "get value without Copy/Clone executing" from Cow::Owned.
Cow<T> -> T without Copy/Clone.
Is the mem::take nice way for it?

You can't go from Cow<'_, T> -> T infallibly without cloning because in the Cow::Borrowed case it only contains a &T, which you need to clone to get a T from. You can easily go from &Cow<'_, T> -> &T by just doing &*cow.

The into_owned method will not clone the data if it is a Cow::Owned.

2 Likes

You can also match on the Cow to move out of it and decide what do do in each case:

match cow {
    Cow::Owned(val) => { /* do stuff with val */ }
    Cow::Borrowed(reference) => { /* ??? */ }
}
4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.