所以特征对象不能有泛型的方法——看起来不错。但是在这种语言中,使用抽象机制的唯一方法是通过泛型和特征对象。这意味着对于每个特征,我必须事先决定它是否可以用作对象,并在任何地方使用 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>,
}