I'm looking for a way to create collection of trait objects. However I would like to accept either objects that implements given trait, or objects that wraps and dereferences to a trait.
trait TheTrait {
// fn foo() -> ();
}
// "Direct" implementation
struct Implements {}
impl TheTrait for Implements {}
// "Proxy" implementation
struct DerefsTo {
implements: Implements,
}
impl std::ops::Deref for DerefsTo {
type Target = dyn TheTrait;
fn deref(&self) -> &Self::Target {
return &self.implements;
}
}
fn main() -> () {
let x1: Box<dyn TheTrait> = Box::new(Implements {}); // This is fine
let x2: Box<dyn TheTrait> = Box::new(DerefsTo {implements: Implements {}}); // Trait TheTrait not implemented
let x3: Box<dyn TheTrait> = Box::new(x1); // Trait TheTrait not implemented
// Put x1, x2, x3 to collection, call foo
}
Is there any way to do this, possibly without touching Implements
type? Is there any generic way to implement a trait by exposing a field that implements it, for example for "wrapper" types?
You may want to
impl<T: std::ops::Deref<Target = dyn TheTrait>> TheTrait for T
This allows you to write:
trait TheTrait {
fn foo(&self) -> ();
}
// "Direct" implementation
struct Implements {}
impl TheTrait for Implements {
fn foo(&self) {
println!("Implements::foo")
}
}
// "Proxy" implementation
struct DerefsTo {
implements: Implements,
}
impl std::ops::Deref for DerefsTo {
type Target = dyn TheTrait;
fn deref(&self) -> &Self::Target {
return &self.implements;
}
}
impl<T: std::ops::Deref<Target = dyn TheTrait>> TheTrait for T {
fn foo(&self) {
self.deref().foo() // forward call
}
}
fn main() -> () {
let x1: Box<dyn TheTrait> = Box::new(Implements {});
let x1_2: Box<dyn TheTrait> = Box::new(Implements {});
let x2: Box<dyn TheTrait> = Box::new(DerefsTo {
implements: Implements {},
});
let x3: Box<dyn TheTrait> = Box::new(x1_2);
let vec = vec![x1, x2, x3];
for x in vec {
x.foo();
}
}
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.