Lets suppose I have a trait
trait A {
fn new() -> Self where Self : Sized;
fn foo(&self) -> i32;
}
struct B {
data : i32
}
impl A for B {
fn new() -> Self {
B {data : 42}
}
fn foo(&self) -> i32 {
self.data
}
}
Now I can use Box<dyn A>
, I just do not have the new() method available. And when I have a generic T: A
, I can do T::new()
. So I can use A as a trait object (without the functions which would prevent this) and I can use it in a templated code and use all functions on it.
My question is, is it possible to get this behavior when having for example Clone
as supertrait? In the dyn A
case A
does not implement Clone. In the generic case is does.
You can do like that:
trait A {
fn new() -> Self where Self : Sized;
fn foo(&self) -> i32;
}
#[derive(Clone)]
struct B {
data : i32
}
impl A for B {
fn new() -> Self {
B {data : 42}
}
fn foo(&self) -> i32 {
self.data
}
}
fn make_clone<T: Clone + A>(toc: &T) -> T {
dbg!(toc.foo());
toc.clone()
}
fn main() {
let b = B{data: 0};
make_clone(&b);
}
so you can access A
method and the Clone
supertrait from make_clone
, you can obviously do the same thing with a supertrait instead of a generic method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.