【发布时间】:2019-05-05 17:46:23
【问题描述】:
我有 DoSomethingProvider 特征,它期望其函数之一的参数为特征类型 DoSomethingListener。
我有一个具体的结构 DoSomethingManager,它有一个类型为 DoSomethingProvider 的成员,并将实现 DoSomethingListener 特征并将其作为侦听器传递给 DoSomethingProvider。
希望代码能说明我正在尝试做的事情:
pub trait DoSomethingListener {
fn something_was_done(msg: &str);
}
pub trait DoSomethingProvider<'a, T>
where
T: DoSomethingListener,
{
fn add_do_something_listener(listener: T);
}
/* note: The struct below will implement DoSomethingListener, and has
* a DoSomethingProvider field. It will pass itself as a listener to
* DoSomethingProvider (which listens to a message queue and notifies
* listeners of certain events)
*/
//this doesn't work. Compiler complains about unused type T
pub struct DoSomethingManager<'a, B, T>
where
T: DoSomethingListener,
B: DoSomethingProvider<'a, T>,
{
provider: Box<B>,
// doesn't have any member of type T
}
// ...
/* So I tried this:
* this doesn't work. Compiler complains that DoSomethingProvider
* expects one type parameter
*/
pub struct DoSomethingManager<'a, B>
where
B: DoSomethingProvider<'a>,
{
provider: Box<B>,
// doesn't have any member of type T
}
//...
/* this compiles, but its a hack */
pub struct DoSomethingManager<'a, B, T>
where
T: DoSomethingListener,
B: DoSomethingProvider<'a, T>,
{
provider: Box<B>,
dummy: Box<T>,
// added unused dummy member of type T
}
我是一位经验丰富的 Python 开发人员,但我是 Rust 新手。在 Rust 中实现这种多态代码的正确方法是什么?
【问题讨论】: