rsactor-derive 0.13.0

Derive macros for rsActor framework
Documentation

Derive macros for rsActor framework

This crate provides derive macros for the rsActor framework, allowing users to automatically implement common traits with sensible defaults.

Actor Derive Macro

The #[derive(Actor)] macro provides a convenient way to implement the Actor trait for simple structs and enums that don't require complex initialization logic.

Generated Implementation

When you use #[derive(Actor)], it generates:

  • Args type set to Self (the struct or enum itself)
  • Error type set to std::convert::Infallible (never fails)
  • on_start method that simply returns the provided args

Usage

With Structs

use rsactor::Actor;

#[derive(Actor)]
struct MyActor {
    name: String,
    count: u32,
}

With Enums

use rsactor::Actor;

#[derive(Actor)]
enum StateActor {
    Idle,
    Processing(String),
    Completed(i32),
}

This is equivalent to manually writing:

# struct MyActor { name: String, count: u32 }
use rsactor::{Actor, ActorRef};
use std::convert::Infallible;

impl Actor for MyActor {
    type Args = Self;
    type Error = Infallible;

    async fn on_start(
        args: Self::Args,
        _actor_ref: &ActorRef<Self>,
    ) -> std::result::Result<Self, Self::Error> {
        Ok(args)
    }
}

When to Use

Use the derive macro when:

  • Your actor doesn't need complex initialization
  • You want to pass a fully constructed instance to spawn()
  • You don't need custom error handling during initialization

For complex initialization (async resource setup, validation, etc.), implement the Actor trait manually.

Message Handlers Attribute Macro

The #[message_handlers] attribute macro combined with #[handler] method attributes provides an automated way to generate Message trait implementations and register message handlers.

Usage

use rsactor::{Actor, ActorRef, message_handlers};

#[derive(Actor)]
struct MyActor {
    count: u32,
}

struct Increment;
struct GetCount;

#[message_handlers]
impl MyActor {
    #[handler]
    async fn handle_increment(&mut self, _msg: Increment, _: &ActorRef<Self>) -> u32 {
        self.count += 1;
        self.count
    }

    #[handler]
    async fn handle_get_count(&mut self, _msg: GetCount, _: &ActorRef<Self>) -> u32 {
        self.count
    }

    // Regular methods without #[handler] are left unchanged
    fn internal_method(&self) -> u32 {
        self.count * 2
    }
}

Benefits

  • Automatic generation of Message<T> trait implementations
  • Selective processing: only methods with #[handler] attribute are processed
  • Reduced boilerplate and potential for errors
  • Type-safe message handling with compile-time checks