Skip to content

Instantly share code, notes, and snippets.

@fchabouis
Created January 7, 2021 14:51
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 fchabouis/10d26b6d5fb36f2d3474bf6abbb2bd41 to your computer and use it in GitHub Desktop.
Save fchabouis/10d26b6d5fb36f2d3474bf6abbb2bd41 to your computer and use it in GitHub Desktop.
Rust Actix simple Actor communication - Arc Version
use actix::prelude::*;
use std::sync::Arc;
/// Define message
#[derive(Message)]
#[rtype(result = "Result<Arc<String>, std::io::Error>")]
struct WhatsYourName;
#[derive(Message)]
#[rtype(result = "()")]
struct SetYourName {
name: Arc<String>,
}
struct MyActor {
name: Arc<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<Arc<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: Arc::new(String::from("Francis")),
}
.start();
ask_and_print_name(&addr).await;
addr.send(SetYourName {
name: Arc::new(String::from("John")),
})
.await;
ask_and_print_name(&addr).await;
// stop system and exit
System::current().stop();
}
@fchabouis
Copy link
Author

fchabouis commented Jan 7, 2021

Context

Same as this gist, but using an Arc of String instead of a a String. Thus avoiding to copy the name data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment