Created
October 19, 2015 22:33
-
-
Save gamazeps/55132c6a0d246af49998 to your computer and use it in GitHub Desktop.
Les messages et la contravariances sont réglés \o/
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 std::any::Any; | |
use std::collections::VecDeque; | |
enum Message { | |
Command(String), | |
Data(Box<Any>), | |
} | |
trait Actor { | |
fn receive(&mut self, Message); | |
fn handle_message(&mut self); | |
} | |
struct Printer { | |
message_queue: VecDeque<Message> | |
} | |
impl Printer { | |
fn new() -> Printer { | |
Printer { | |
message_queue: VecDeque::new() | |
} | |
} | |
} | |
impl Actor for Printer { | |
fn receive(&mut self, message: Message) { | |
self.message_queue.push_back(message); | |
} | |
fn handle_message(&mut self) { | |
let message = self.message_queue.pop_front().unwrap(); | |
match message { | |
Message::Command(command) => { | |
println!("Received Command: ({})", command) | |
}, | |
Message::Data(truc) => { | |
match truc.downcast_ref::<String>() { | |
Some(s) => println!("Received data: ({})", s), | |
None => println!("Message is dropped"), | |
} | |
} | |
} | |
} | |
} | |
fn main() { | |
let message = "This is a message".to_string(); | |
let command = "This is a command".to_string(); | |
let mut actor = Printer::new(); | |
actor.receive(Message::Command(command)); | |
actor.receive(Message::Data(Box::new(message))); | |
actor.receive(Message::Data(Box::new(3i32))); | |
actor.handle_message(); | |
actor.handle_message(); | |
actor.handle_message(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment