Skip to content

Instantly share code, notes, and snippets.

@thbar
Forked from fchabouis/main.rs
Created January 7, 2021 14:56
Show Gist options
  • Select an option

  • Save thbar/a28eeb55c6bdc9e36cc942b76fca0346 to your computer and use it in GitHub Desktop.

Select an option

Save thbar/a28eeb55c6bdc9e36cc942b76fca0346 to your computer and use it in GitHub Desktop.

Revisions

  1. @fchabouis fchabouis renamed this gist Jan 7, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @fchabouis fchabouis created this gist Jan 7, 2021.
    72 changes: 72 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -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();
    }