Trait returning reference to an Actix Actor

Hi all! I am really struggling to understand how to make a trait object to return a reference to an actor. I am trying this:

pub trait Driver: Send + Sync {
    fn get_info(&self) -> DriverInfo;
    fn validate_config(&self, config: Value) -> bool;
    fn get_actor(&self) -> WeakAddr<dyn Actor<Context = ()>>;
}

But obviously dyn Actor<Context = ()> is not Sized. But if I wrap it inside a Box, then the trait actix::actor::Actor is not implemented for std::boxed::Box<(dyn actix::actor::Actor<Context = ()> + 'static)>.

How can I make a Trait that is capable of returning a reference to an actor?

Thanks everyone :wink:

1 Like

I'm not familiar with actix, but the usual approach is something like this:

pub trait Driver: Send + Sync {
    type MyActor: Actor<Context = ()>;
    fn get_info(&self) -> DriverInfo;
    fn validate_config(&self, config: Value) -> bool;
    fn get_actor(&self) -> WeakAddr<Self::MyActor>;
}

Hi, thanks for your reply!!

The Driver trait is supposed to be implemented by various structs. Each defining a different Actor struct.

Then this impl Driver structs are to be contained within a HashMap, so, AFAIK, trait objects are necessary here. And unfortunately, Actor trait is Sized so it cannot be used in trait objects.

the trait actix::actor::Actor cannot be made into an object.

Do you have any suggestion to do this without trait objects?

Thank you very much for your time :wink:

I have a similar problem. I want to add MyActor (Driver) to the hashmap.

#[derive(Debug, Clone)]
struct Driver {
    data_hub_addr: Addr<DataHub>,
}

/// Declare actor and its context
impl Actor for Driver {
    type Context = Context<Self>;

	fn started(&mut self, ctx: &mut Context<Self>) {
          println!("Actor is alive");

            ctx.run_interval(Duration::from_secs(1), |actor, ctx| {
            println!("Driver interval");
            unsafe
            {
                    static mut i: u32 = 0;
                    i = i + 1;
                    actor.data_hub_addr.do_send(Data::new(i as u32));
                }
            });
       }

    fn stopped(&mut self, ctx: &mut Context<Self>) {
       println!("Actor is stopped");
    }
}

Running:

for (_name, drv) in self.drv_map {
        Arbiter::start(move |_| drv );
    }

Error:

 Arbiter::start(move |_| drv );
    |             ^^^^^^^^^^^^^^ the trait `actix::actor::Actor` is not implemented for `std::boxed::Box<state::Driver>`

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.