danda
danda

Reputation: 661

When does to_owned() not clone?

The docs for to_owned() state:

Creates owned data from borrowed data, usually by cloning.

But it is unstated the conditions under which cloning does not occur. "Usually" is quite vague, and I am trying to remove .clone() calls for performance reasons.

Can someone clarify?

Upvotes: 15

Views: 3777

Answers (1)

joshmeranda
joshmeranda

Reputation: 3251

The to_owned method is part of the ToOwned trait, because of this it cannot guarantee that the struct implementing the trait will clone or not clone the instance to_owned is being called upon. The blanket implementation for the ToOwned trait does call clone, and it is rarely manually implemented, which is one of the reasons almost every call to to_owned will result in a cloning.

Additionally, as pointed out by @Sven Marnach, any struct which derives Clone receives the blanket implementation and cannot implement its own implementation of ToOwned, making calls to the blanket imp even more common.

See below for the blanket implementation of ToOwned

impl<T> ToOwned for T
where
    T: Clone,
{
    type Owned = T;
    fn to_owned(&self) -> T {
        self.clone()
    }

    fn clone_into(&self, target: &mut T) {
        target.clone_from(self);
    }
}

Upvotes: 10

Related Questions