fork download
  1. // ======================= library side =======================
  2.  
  3. // this is a simplified version of the actor trait
  4. // a trait is something like an interface
  5. trait Actor {
  6. type Msg;
  7.  
  8. // the trait defines the recv function
  9. // this function must be implemented by the user
  10. // and gets called by the actor system when a message arrives
  11. fn recv(&mut self, msg: Self::Msg);
  12. }
  13.  
  14.  
  15.  
  16. // this is simplification of what happens when a message arrives for an actor
  17. fn execute_message<A>(actor: &mut A, msg: A::Msg)
  18. where A: Actor,
  19. {
  20. actor.recv(msg);
  21. }
  22.  
  23.  
  24.  
  25. // this is a simplification of what happens when a message gets sent
  26. fn send_message<A>(actor: &mut A, msg: A::Msg)
  27. where A: Actor,
  28. {
  29. // normaly the message would first land in the messagebox of the actor
  30. // when the actor starts it's work, it takes a message from the messagebox and executes it
  31. // in order to simplify, we call execute directly
  32. execute_message(actor, msg);
  33. }
  34.  
  35. // ============================================================
  36.  
  37.  
  38.  
  39.  
  40. // ======================== user side =========================
  41.  
  42. // User-defined actor struct
  43. struct MyActor {
  44. i: i32,
  45. }
  46.  
  47. // the implementation of the Actor trait
  48. impl Actor for MyActor {
  49. type Msg = String;
  50. fn recv(&mut self, msg: String) {
  51. println!("i: {}, msg: {}", self.i, msg);
  52. }
  53. }
  54.  
  55. fn main() {
  56. let mut a = MyActor { i: 10 };
  57. send_message(&mut a, "test".to_string());
  58. }
  59.  
  60. // ============================================================
Success #stdin #stdout 0s 4400KB
stdin
Standard input is empty
stdout
i: 10, msg: test