我有一个DoSomethingProvidertrait,它期望它的一个函数的参数是trait类型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中实现此多态代码的正确方法是什么?

最佳答案

DoSomethingProvider更改为使用associated type而不是侦听器类型的类型参数。

pub trait DoSomethingListener {
    fn something_was_done(msg: &str);
}

pub trait DoSomethingProvider {
    type Listener: DoSomethingListener;

    fn add_do_something_listener(listener: Self::Listener);
}

pub struct DoSomethingManager<B>
where
    B: DoSomethingProvider,
{
    provider: Box<B>,
}

请注意,通过使用关联类型或类型参数,DoSomethingProvider的特定实例将只能接受单个特定类型的侦听器。如果您希望能够注册各种类型的侦听器,则需要通过trait objects使用动态调度。

10-02 02:26