Skip to content

Instantly share code, notes, and snippets.

@thbar
Forked from fchabouis/main.rs
Created January 7, 2021 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thbar/a28eeb55c6bdc9e36cc942b76fca0346 to your computer and use it in GitHub Desktop.
Save thbar/a28eeb55c6bdc9e36cc942b76fca0346 to your computer and use it in GitHub Desktop.
Rust Actix simple Actor communication
use actix::prelude::*;
/// Define message
#[derive(Message)]
#[rtype(result = "Result<String, std::io::Error>")]
struct WhatsYourName;
#[derive(Message)]
#[rtype(result = "()")]
struct SetYourName {
name: String,
}
struct MyActor {
name: String,
}
impl Actor for MyActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Context<Self>) {
println!("Actor {} is alive", self.name);
}
}
/// Define handler for `WhatsYourName` message
impl Handler<WhatsYourName> for MyActor {
type Result = Result<String, std::io::Error>;
fn handle(&mut self, msg: WhatsYourName, ctx: &mut Context<Self>) -> Self::Result {
Ok(self.name.clone())
}
}
/// Define handler for `SetYourName` message
impl Handler<SetYourName> for MyActor {
type Result = ();
fn handle(&mut self, msg: SetYourName, ctx: &mut Context<Self>) -> Self::Result {
self.name = msg.name.clone();
println!("New name {} is set", msg.name);
}
}
async fn ask_and_print_name(addr: &Addr<MyActor>) {
let result = addr.send(WhatsYourName).await;
match result {
Ok(res) => println!("Got result: {}", res.unwrap()),
Err(err) => println!("Got error: {}", err),
}
}
#[actix_rt::main]
async fn main() {
// start new actor
let addr = MyActor {
name: String::from("Francis"),
}
.start();
ask_and_print_name(&addr).await;
addr.send(SetYourName {
name: String::from("John"),
})
.await;
let result = addr.send(WhatsYourName).await;
ask_and_print_name(&addr).await;
// stop system and exit
System::current().stop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment