[英]How can a trait object take a trait with generic methods as an argument?
所以 trait 對象不能有帶有泛型的方法——這看起來不錯。 但是在這種語言中,使用抽象機制的唯一方法是通過泛型和特征對象。 這意味着對於每個特征,我必須事先決定它是否可以用作對象並在那里到處使用 dyn 而不是 impl。 並且必須以相同的方式制作其中的所有特征以支持這一點。 這種感覺非常難看。 你能提出什么建議或告訴我為什么它是這樣設計的嗎?
fn main() {}
// some abstracted thing
trait Required {
fn f(&mut self, simple: i32);
}
// this trait doesn't know that it's going to be used by DynTrait
// it just takes Required as an argument
// nothing special
trait UsedByDyn {
// this generic method doesn't allow this trait to be dyn itself
// no dyn here: we don't know about DynTrait in this scope
fn f(&mut self, another: impl Required);
}
// this trait needs to use UsedByDyn as a function argument
trait DynTrait {
// since UsedByDyn uses generic methods it can't be dyn itself
// the trait `UsedByDyn` cannot be made into an object
//fn f(&mut self, used: Box<dyn UsedByDyn>);
// we can't use UsedByDyn without dyn either otherwise Holder can't use us as dyn
// the trait `DynTrait` cannot be made into an object
// fn f(&mut self, used: impl UsedByDyn);
// how to use UsedByDyn here?
}
struct Holder {
CanBeDyn: Box<dyn DynTrait>,
}
這意味着對於每個特征,我必須事先決定它是否可以用作對象並在那里到處使用 dyn 而不是 impl。
您可以這樣做,但幸運的是,這不是唯一的選擇。
你也可以像往常一樣編寫你的特征,在適當的地方使用泛型。 如果/當您需要 trait 對象時,定義一個您在本地使用的新的對象安全 trait,並在該位置公開您實際需要的 API 子集。
例如,假設您擁有或使用非對象安全特性:
trait Serialize {
/// Serialize self to the given IO sink
fn serialize(&self, sink: &mut impl io::Write);
}
該 trait 不能用作 trait 對象,因為它(大概是為了確保最大效率)有一個通用方法。 但這並不需要阻止您的代碼使用 trait 對象來訪問 trait 的功能。 假設您需要向框Serialize
,以保持他們在一個載體,你會保存到一個文件中集體值:
// won't compile
struct Pool {
objs: Vec<Box<dyn Serialize>>,
}
impl Pool {
fn add(&mut self, obj: impl Serialize + 'static) {
self.objs.push(Box::new(obj) as Box<dyn Serialize>);
}
fn save(&self, file: &Path) -> io::Result<()> {
let mut file = io::BufWriter::new(std::fs::File::create(file)?);
for obj in self.objs.iter() {
obj.serialize(&mut file);
}
Ok(())
}
}
上面的代碼無法編譯,因為Serialize
不是對象安全的。 但是 - 您可以輕松定義滿足Pool
需求的新對象安全特性:
// object-safe trait, Pool's implementation detail
trait SerializeFile {
fn serialize(&self, sink: &mut io::BufWriter<std::fs::File>);
}
// Implement `SerializeFile` for any T that implements Serialize
impl<T> SerializeFile for T
where
T: Serialize,
{
fn serialize(&self, sink: &mut io::BufWriter<std::fs::File>) {
// here we can access `Serialize` because `T` is a concrete type
Serialize::serialize(self, sink);
}
}
現在Pool
幾乎可以正常工作,使用dyn SerializeFile
( playground ):
struct Pool {
objs: Vec<Box<dyn SerializeFile>>,
}
impl Pool {
fn add(&mut self, obj: impl Serialize + 'static) {
self.objs.push(Box::new(obj) as Box<dyn SerializeFile>);
}
// save() defined the same as before
...
}
定義一個單獨的對象安全特性似乎是不必要的工作——如果原始特性足夠簡單,你當然可以從一開始就讓它成為對象安全的。 但是有些特征要么太籠統,要么太注重性能,以至於不能從一開始就成為對象安全的,在這種情況下,最好記住保持它們的通用性是可以的。 當您確實需要一個對象安全版本時,它通常用於具體任務,其中根據原始特征實現的自定義對象安全特征將完成這項工作。
我使用了@user4815162342 的答案,但制作了我自己的版本,不需要用具體類型替換非對象友好特性。
struct Holder {
dyn_traits: Vec<Box<dyn DynTrait>>,
}
// this trait doesn't know that it's going to be used by DynTrait
// it just takes ObjectFriendly as an argument
// nothing special
trait ObjectUnfriendly {
// this generic method doesn't allow this trait to be dyn itself
// no dyn here: we don't know about DynTrait in this scope
fn f(&mut self, another: &impl ObjectFriendly);
fn f2(&mut self, another: &mut impl ObjectFriendly);
fn f3(&mut self, another: impl ObjectFriendly);
}
trait ObjectFriendly {
fn f(&mut self, simple: i32);
fn f2(&self, simple: i32);
}
// this trait needs to use the trait above as a function argument
trait DynTrait {
// since that trait uses generic methods it can't be dyn itself
// the trait cannot be made into an object
//fn f(&mut self, used: Box<dyn ObjectUnfriendly>);
// we can't use that trait without dyn either otherwise Holder can't use us as dyn
// the trait `DynTrait` cannot be made into an object
// fn f(&mut self, used: impl ObjectUnfriendly);
// how to use ObjectUnfriendly here?
// we use our own extension trait that is object-friendly
fn f(&mut self, used: dyn NowObjectFriendly);
}
// our own object-friendly version
trait NowObjectFriendly {
// if arguments are ObjectFriendly - we are lucky
fn f(&mut self, another: &dyn ObjectFriendly);
fn f2(&mut self, another: &mut dyn ObjectFriendly);
fn f3(&mut self, another: Box<dyn ObjectFriendly>);
// if not - we can just accept the specific struct we need
// fn f3(&mut self, another: SomeImpl);
// or do the same thing by making an extension trait
// fn f3(&mut self, another: Box<dyn ObjectFriendly2Ex>);
}
// delegate implementation
impl<T: ObjectUnfriendly> NowObjectFriendly for T {
fn f(&mut self, another: &dyn ObjectFriendly) {
self.f(&ObjectFriendly2AsImpl(another));
}
fn f2(&mut self, another: &mut dyn ObjectFriendly) {
self.f2(&mut ObjectFriendly2AsImpl(another));
}
fn f3(&mut self, another: Box<dyn ObjectFriendly>) {
self.f3(ObjectFriendly2AsImpl(another));
}
// if not object friendly - we can just accept the specific struct we need
// fn f3(&mut self, another: SomeImpl) {
// SomeImpl::f3(self, another);
// }
// or do the same thing for that trait by making another extension trait
// fn f3(&mut self, another: Box<dyn ObjectFriendly2Ex>) {
// self.f3(another);
// }
}
// for this delegation to work
// we need to make it convertible to impl
// can't implement foreign traits on foreign types
struct ObjectFriendly2AsImpl<T>(T);
impl ObjectFriendly for ObjectFriendly2AsImpl<&dyn ObjectFriendly> {
fn f(&mut self, simple: i32) {
unreachable!()
}
fn f2(&self, simple: i32) {
(*self.0).f2(simple)
}
}
impl ObjectFriendly for ObjectFriendly2AsImpl<&mut dyn ObjectFriendly> {
fn f(&mut self, simple: i32) {
(*self.0).f(simple)
}
fn f2(&self, simple: i32) {
(*self.0).f2(simple)
}
}
impl ObjectFriendly for ObjectFriendly2AsImpl<Box<dyn ObjectFriendly>> {
fn f(&mut self, simple: i32) {
(*self.0).f(simple)
}
fn f2(&self, simple: i32) {
(*self.0).f2(simple)
}
}
如果有針對此或更輕量級實現的宏,請發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.