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?
The ToOwned trait generalizes Clone to construct owned data from any borrow of a given type.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With