Rust那些事之ToOwned trait

发布于:2024-04-15 ⋅ 阅读:(160) ⋅ 点赞:(0)

Rust那些事之ToOwned trait

默认的Clone trait有两个问题:

  • 只支持固定大小的类型

  • 转换也只能从&T到T,不能够从&T到U的转换。

pub trait Clone: Sized

那么如何实现呢?于是便有了ToOwned trait。

ToOwned内部有一个关联类型Owned,实现ToOwned要求其实现Borrow trait。

pub trait ToOwned {
    type Owned: Borrow<Self>;
    fn to_owned(&self) -> Self::Owned;
    fn clone_into(&self, target: &mut Self::Owned) {
        *target = self.to_owned();
    }
}

例如str的ToOwned实现如下,可以从&str变为String类型。

impl ToOwned for str {
    type Owned = String;
    #[inline]
    fn to_owned(&self) -> String {
        unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
    }

    fn clone_into(&self, target: &mut String) {
        let mut b = mem::take(target).into_bytes();
        self.as_bytes().clone_into(&mut b);
        *target = unsafe { String::from_utf8_unchecked(b) }
    }
}

ToOwned也有默认的实现,对于任意类型T必须要求其实现Clone trait,然后调用Clone的接口。即:默认实现等价于Clone的实现。

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);
    }
}

往期回顾:

我的春招求职面经

热度更新,手把手实现工业级线程池

d65d8bae740cb8d25399b17c3e5faf1d.jpeg

e24f48b7c572cec8e0e3ecd30ec0d5c6.jpeg


网站公告

今日签到

点亮在社区的每一天
去签到