Trait dyn_context::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; 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, StateExt}; use macro_attr_2018::macro_attr; use std::convert::Into; macro_attr! { #[derive(State!)] struct PrintState { value: String } } 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 dyn_context::{free_lifetimes, State, StateExt}; use call_back::CallBack; free_lifetimes! { struct PrintState { value: 'value ref str } } State!(() struct 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));
Because the free_lifetimes!
macro cannot be used simultaneously
with macro_attr!
,
the State!
macro deriving State
trait implementation used here in standalone mode.
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.