swactor/examples/hello.rs
Zachery Aaron Shores-Chmielewski c62b20c732 feat(WIP): refactor router execution
In single threaded contexts, the Router now is treated as yet another actor
on the queue. In multithreaded contexts, it gets its own dedicated thread.
2026-01-25 12:54:01 +07:00

59 lines
1.3 KiB
Rust

use swactor::{
actor::{ActorAddress, ActorInterface},
runtime::{Runtime, RuntimeFlavor},
};
#[derive(Debug, Default)]
struct Greeter {
pub num_greeted: usize,
}
#[derive(Debug, Default, Clone)]
struct GreetMessage {
/// who do we greet?
who: String,
/// who do we send out greeting back to?
return_addr: ActorAddress,
}
#[derive(Debug, Default, Clone)]
struct GreetResponse(String);
impl ActorInterface for Greeter {
type Incoming = GreetMessage;
type Response = GreetResponse;
fn handle(&mut self, ctx: &Runtime, msg: GreetMessage) {
let res = GreetResponse(format!("Hello, {}!", msg.who));
self.num_greeted += 1;
if let Err(_) = ctx.send_to(msg.return_addr, res) {
// no error handling
self.num_greeted -= 1;
}
}
}
fn main() {
let mut rt = Runtime::new();
let addr = rt
.spawn(Greeter::default())
.expect("failed to spawn greeter");
let inbox = rt.new_inbox::<GreetResponse>();
rt.send_to(
addr,
GreetMessage {
who: "world".into(),
return_addr: *inbox.addr(),
},
)
.unwrap();
for _ in 0..3 {
rt.tick();
}
let resp = inbox.try_recv().expect("greeter should have said hello");
println!("{}", resp.0);
}