[英]Generic type for types implementing trait or dereferencing to 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
}
有什么辦法可以做到這一點,可能不需要觸及Implements
類型? 是否有任何通用方法通過公開實現它的字段來實現特性,例如“包裝器”類型?
你可能想要
impl<T: std::ops::Deref<Target = dyn TheTrait>> TheTrait for T
這允許您編寫:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.