- handle_event self,
fn handle_event(mut self, ...) -> Option<Self>: Rc<RefCell<>> Box<State> , - , .
, . Rc Box, : Rc::try_unwrap Rc.
, Dispatcher:
struct Dispatcher {
states: HashMap<Uid, Rc<State>>,
}
impl Dispatcher {
fn dispatch(&mut self, state_id: Uid, event: Event) {
if let Some(state_ref) = self.states.remove(&state_id) {
let state = state_ref.try_unwrap()
.expect("Unique strong reference required");
if let Some(next_state) = state.handle_event(event) {
self.states.insert(state_id, next_state);
}
} else {
}
}
}
(: dispatch state_id . - . , state_id HashMap::insert. , Uid Copy, .)
, state_id , State , handle_event - impl Dispatcher, State Dispatcher.
impl State for S0 {
fn handle_event(self, event: Event) -> Option<Rc<State>> {
if event == Event::SomeEvent {
// Do some work
let next_state = Rc::new(S0 {
state_id: self.state_id,
move_only_field: self.mof,
});
Some(next_state)
} else {
// Do some other work
}
}
}
, , Option None.
, , - / , Weak<RefCell<>> , "" .. .
Rc, , .
" " , , , , fn handle_event(mut self, ...) -> Option<Self>, . impl State for ... , , , , . , - dispatcher.insert(state_id, next_state), . handle_event self , - .
( , , - , dispatch : , , . lookup, : Option<Rc<State>> HashMap take Option .)