Attribute Macro simpl_actor::actor

source ·
#[actor]
Expand description

Attribute macro placed on impl blocks of actors to defined messages.

Methods on the impl block are marked with #[message], allowing them to be called on the actor.

Under the hood, this macro generates the following (among other things):

  • pub struct MyActorRef: a reference to this actor which implements ActorRef and has methods to interact with the actor based on the messages defined.
  • enum MyActorMsg: a private message enum used in the mpsc channel.
  • impl Spawn for MyActor: an implementation of Spawn, allowing the actor to be spawned.

The actor being implemented should implement Actor either with the derive macro, or manually.

Note that generics are not supported in messages, instead dyn trait objects should be used.

§Example

#[actor]
impl MyActor {
    pub fn new() -> Self { ... }

    /// A message with no return value
    #[message]
    pub fn inc(&mut self, amount: i64) {
        self.count += amount;
    }

    /// A message returning a value
    #[message]
    pub fn count(&self) -> i64 {
        self.count
    }

    /// A message that uses async
    #[message]
    pub async fn sleep(&self) {
        tokio::time::sleep(Duration::from_millis(500)).await;
    }

    /// A message that sends a message to itself
    #[message]
    pub async fn inc_myself(&self) -> Result<(), ActorError<i64>> {
        self.actor_ref().inc_async(1).await
    }
}