|
|
@@ -0,0 +1,72 @@ |
|
|
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(); |
|
|
} |