Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does to_owned() not clone?

Tags:

rust

borrowing

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?

like image 832
danda Avatar asked Aug 24 '20 02:08

danda


People also ask

What does To_owned do in Rust?

The ToOwned trait generalizes Clone to construct owned data from any borrow of a given type.

How do you duplicate String in Rust?

The only correct way to copy a String is to allocate a new block of heap memory to copy all the characters into, which is what String 's Clone implementation does. What is Ownership? - The Rust Programming Language covers these topics in much more detail.


1 Answers

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);
    }
}
like image 177
joshmeranda Avatar answered Sep 28 '22 22:09

joshmeranda