Skip to content

Instantly share code, notes, and snippets.

@fchabouis
Created January 7, 2021 14:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fchabouis/a473978b34afa0a2c1d288d312eadf5f to your computer and use it in GitHub Desktop.
Save fchabouis/a473978b34afa0a2c1d288d312eadf5f 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();
}
@fchabouis
Copy link
Author

Context

Play a little bit with the Rust Actix library.

Goal

Create an actor that holds a name. Create two possible messages for that Actor :

  • WhatsYourName asks for the actor name
  • SetYourName sets a new name for the Actor

Interesting thing

When the Actor receives a WhatsYourName message, it needs to clone the underlying String to send it back. What if this name is some really big data ? Do I need to clone it for each incoming request ?

In that case, I need to use an Arc, the rust concept for a shared pointer.
See the second gist for that case.

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