pub fn spawn<A: Actor>(spec: A::Spec) -> Link<A>Expand description
Spawn a new actor instance with the given specification.
This is a convenience function that delegates to the actor’s associated
spawn method, providing a unified interface for actor creation.
§Arguments
spec- The specification required to initialize the actor
§Returns
A Link<A> that can be used to send messages to the spawned actor.
§Examples
use actor12::{spawn, Actor, Init, Exec, MpscChannel, Multi};
struct MyActor;
impl Actor for MyActor {
type Message = Multi<Self>;
type Spec = ();
type Channel = MpscChannel<Self::Message>;
type Cancel = ();
type State = ();
fn state(_spec: &Self::Spec) -> Self::State {
()
}
fn init(_ctx: Init<'_, Self>) -> impl std::future::Future<Output = Result<Self, Self::Cancel>> + Send + 'static {
std::future::ready(Ok(MyActor))
}
}
// Spawn the actor
let link = spawn::<MyActor>(());Examples found in repository?
examples/echo_server.rs (line 35)
34async fn main() -> anyhow::Result<()> {
35 let echo_server = spawn::<EchoServer>(());
36
37 let messages = vec!["Hello", "World", "How are you?", "Goodbye"];
38
39 for message in messages {
40 let response: anyhow::Result<String> = echo_server.send(message.to_string()).await;
41 println!("Received: {}", response?);
42 }
43
44 Ok(())
45}More examples
examples/ping_pong.rs (line 198)
196async fn main() -> anyhow::Result<()> {
197 // Spawn ping and pong actors
198 let ping = spawn::<PingPong>(true);
199 let pong = spawn::<PingPong>(false);
200
201 // Connect them
202 let _ = ping.ask_dyn(Connect(pong.clone())).await;
203 let _ = pong.ask_dyn(Connect(ping)).await;
204
205 // Wait for the game to finish
206 sleep(Duration::from_secs(2)).await;
207
208 Ok(())
209}examples/basic_actor.rs (line 72)
70async fn main() -> anyhow::Result<()> {
71 // Spawn a counter actor with initial value 0
72 let counter = spawn::<Counter>(0);
73
74 // Send increment messages
75 counter.send(()).await?;
76 counter.send(()).await?;
77 counter.send(()).await?;
78
79 println!("Sent 3 increment messages");
80
81 // For demonstration, we'll just show that we can increment
82 // A real multi-message actor would use the Multi<A> pattern
83 // as shown in the integration tests
84
85 Ok(())
86}examples/simple_counter.rs (line 57)
55async fn main() -> anyhow::Result<()> {
56 // Spawn a counter actor with initial value 0
57 let counter = spawn::<Counter>(0);
58
59 // Send increment messages
60 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
61 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
62 let _: anyhow::Result<CounterResponse> = counter.send(CounterRequest::Increment).await;
63
64 // Get the current count
65 let response: anyhow::Result<CounterResponse> = counter.send(CounterRequest::GetCount).await;
66 match response? {
67 CounterResponse::Count(count) => println!("Final count: {}", count),
68 _ => println!("Unexpected response"),
69 }
70
71 Ok(())
72}examples/bank_account.rs (line 141)
139async fn main() -> anyhow::Result<()> {
140 // Create two bank accounts
141 let alice_account = spawn::<BankAccount>(("ALICE-001".to_string(), 1000.0));
142 let bob_account = spawn::<BankAccount>(("BOB-002".to_string(), 500.0));
143
144 // Perform some operations
145 println!("\n=== Initial Operations ===");
146
147 // Check initial balances
148 let alice_balance = alice_account.ask_dyn(GetBalance).await?;
149 let bob_balance = bob_account.ask_dyn(GetBalance).await?;
150 println!("Alice: ${:.2}, Bob: ${:.2}", alice_balance, bob_balance);
151
152 // Alice deposits money
153 let _ = alice_account.ask_dyn(Deposit { amount: 200.0 }).await?;
154
155 // Bob withdraws money
156 let _ = bob_account.ask_dyn(Withdraw { amount: 100.0 }).await?;
157
158 println!("\n=== Transfer Operation ===");
159
160 // Alice transfers money to Bob
161 alice_account.ask_dyn(Transfer {
162 to_account: bob_account.clone(),
163 amount: 300.0
164 }).await?;
165
166 println!("\n=== Final Balances ===");
167 let alice_final = alice_account.ask_dyn(GetBalance).await?;
168 let bob_final = bob_account.ask_dyn(GetBalance).await?;
169 println!("Alice: ${:.2}, Bob: ${:.2}", alice_final, bob_final);
170
171 println!("\n=== Error Handling ===");
172
173 // Try to withdraw more than available (should fail)
174 match alice_account.ask_dyn(Withdraw { amount: 2000.0 }).await {
175 Ok(_) => println!("Withdrawal succeeded unexpectedly!"),
176 Err(e) => println!("Withdrawal failed as expected: {}", e),
177 }
178
179 // Wait a moment before shutting down
180 sleep(Duration::from_millis(100)).await;
181
182 Ok(())
183}examples/handler_pattern.rs (line 99)
95async fn main() -> anyhow::Result<()> {
96 println!("=== Handler Pattern Example ===\n");
97
98 // Spawn the actor
99 let actor = spawn::<MultiHandlerActor>("CounterBot".to_string());
100
101 // Use different message types with the same actor
102 println!("1. Testing typed messages:");
103
104 // Increment counter
105 let count1: Result<i32, anyhow::Error> = actor.ask_dyn(IncrementMsg).await;
106 println!("Result: {:?}", count1);
107
108 let count2: Result<i32, anyhow::Error> = actor.ask_dyn(IncrementMsg).await;
109 println!("Result: {:?}", count2);
110
111 // Get current count
112 let current: Result<i32, anyhow::Error> = actor.ask_dyn(GetCountMsg).await;
113 println!("Current count: {:?}", current);
114
115 println!("\n2. Testing name operations:");
116
117 // Change name
118 let old_name: Result<String, anyhow::Error> = actor.ask_dyn(SetNameMsg("SuperBot".to_string())).await;
119 println!("Previous name: {:?}", old_name);
120
121 // Get current name
122 let name: Result<String, anyhow::Error> = actor.ask_dyn(GetNameMsg).await;
123 println!("Current name: {:?}", name);
124
125 println!("\n3. Testing dynamic string messages:");
126
127 // Send string messages dynamically
128 let response1: Result<String, anyhow::Error> = actor.ask_dyn("Hello there!".to_string()).await;
129 println!("Response: {:?}", response1);
130
131 let response2: Result<String, anyhow::Error> = actor.ask_dyn("How are you doing?".to_string()).await;
132 println!("Response: {:?}", response2);
133
134 println!("\n4. Final state check:");
135 let final_count: Result<i32, anyhow::Error> = actor.ask_dyn(GetCountMsg).await;
136 let final_name: Result<String, anyhow::Error> = actor.ask_dyn(GetNameMsg).await;
137 println!("Final count: {:?}, Final name: {:?}", final_count, final_name);
138
139 Ok(())
140}Additional examples can be found in: