Created
January 7, 2021 14:51
-
-
Save fchabouis/10d26b6d5fb36f2d3474bf6abbb2bd41 to your computer and use it in GitHub Desktop.
Rust Actix simple Actor communication - Arc Version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Context
Same as this gist, but using an Arc of String instead of a a String. Thus avoiding to copy the name data.