在Rust中,一般通过clone 方法来获取变量的副本。但有的类型,如&str 或 &[u8]等无法通过实现Clone trait 来实现 clone方法。于是便有了ToOwned trait。下面看一下定义:
trait ToOwned {
type Owned: Borrow<Self>;
fn to_owned(&self) -> Self::Owned;
}
下面是实现例子:
use std::borrow::Borrow;
#[derive(Debug)]
struct Any<'a, T> {
content: &'a T,
}
#[derive(Debug)]
struct One<'a, T> {
any: Any<'a, T>,
}
impl<'a, T> std::borrow::Borrow<Any<'a, T>> for One<'a, T> {
fn borrow(&self) -> &Any<'a, T> {
&self.any
}
}
impl<'a, T> std::borrow::ToOwned for Any<'a, T> {
type Owned = One<'a, T>;
fn to_owned(&self) -> Self::Owned {
One {
any: Any {
content: self.content.clone(),
},
}
}
}
fn main() {
let content = "hello".to_owned();
let o = One { any: Any { content: &content },};
let b: &Any<String> = o.borrow();
println!("{:?}", b); // Any { content: "hello" }
let a = Any { content: &content };
let b = a.to_owned();
println!("{:?}", b); // One { any: Any { content: "hello" } }
}