How does the std library implement std::borrow::ToOwned for any T: Clone but also specifically for &str?

⚓ Rust    📅 2026-06-08    👤 surdeus    👁️ 1      

surdeus

The std library uses the trait std::borrow::ToOwned to genericalize the Clone trait.

They implement this trait for any T: Clone

#[stable(feature = "rust1", since = "1.0.0")]
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);
    }
}

And also for a number of type specifically - e.g. for &str:


#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for str {
    type Owned = String;

    #[inline]
    fn to_owned(&self) -> String {
        unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
    }

    #[inline]
    fn clone_into(&self, target: &mut String) {
        target.clear();
        target.push_str(self);
    }
}

How do they do this without getting error conflicting implementation for: ...?

E.g. if i do this like:

// #[derive(Clone)]
struct MyStruct;

trait MyTrait {}
impl<T> MyTrait for T where T: Clone {}
impl MyTrait for MyStruct {}

If i uncomment the derive(Clone) i get this error.

4 posts - 4 participants

Read full topic

🏷️ Rust_feed