Trait dyn_context::state::State [−][src]
pub trait State: 'static {
fn get_raw(&self, ty: TypeId) -> Option<&dyn Any>;
fn get_mut_raw(&mut self, ty: TypeId) -> Option<&mut dyn Any>;
}Expand description
A service provider pattern implementation = associated read-only container with type as a key.
Useful for building complex systems with callbacks without generic parameters.
Examples
mod call_back {
use dyn_context::state::State;
pub struct CallBack {
callback: Option<fn(state: &mut dyn State)>
}
impl CallBack {
pub fn new() -> Self { CallBack { callback: None } }
pub fn set_callback(&mut self, callback: fn(state: &mut dyn State)) {
self.callback.replace(callback);
}
pub fn call_back(&self, state: &mut dyn State) {
self.callback.map(|callback| callback(state));
}
}
}
use call_back::CallBack;
use dyn_context::state::{SelfState, StateExt};
use std::convert::Into;
struct PrintState {
value: String
}
impl SelfState for PrintState { }
let mut call_back = CallBack::new();
call_back.set_callback(|state| {
let print: &PrintState = state.get();
println!("{}", &print.value);
});
call_back.call_back(&mut PrintState { value: "Hello, world!".into() });For using &str instead of String the free_lifetimes! macro can be used:
use call_back::CallBack;
use dyn_context::free_lifetimes;
use dyn_context::state::{SelfState, StateExt};
free_lifetimes! {
struct PrintState {
value: 'value ref str
}
}
impl SelfState for PrintState { }
let mut call_back = CallBack::new();
call_back.set_callback(|state| {
let print: &PrintState = state.get();
println!("{}", print.value());
});
PrintStateBuilder {
value: "Hello, world!"
}.build_and_then(|state| call_back.call_back(state));Required methods
Borrows shareable data entry.
Prefer high-level get wrap.
Trait Implementations
Merges two states into one and calls provided function with the combined state.
fn merge_mut_and_then<T>(
self,
f: impl FnOnce(&mut dyn State) -> T,
other: &mut dyn State
) -> T
fn merge_mut_and_then<T>(
self,
f: impl FnOnce(&mut dyn State) -> T,
other: &mut dyn State
) -> T
Merges two states into one and calls provided function with the combined state.