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
whereT: Clone,
{type Owned = T;fn to_owned(&self) -> T {self.clone()}fn clone_into(&self, target: &mut T) {target.clone_from(self);}
}
往期回顾:
我的春招求职面经
热度更新,手把手实现工业级线程池