Trait dyn_context::Context[][src]

pub trait Context: '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::Context;

    pub struct CallBack {
        callback: Option<fn(context: &mut dyn Context)>
    }

    impl CallBack {
        pub fn new() -> Self { CallBack { callback: None } }

        pub fn set_callback(&mut self, callback: fn(context: &mut dyn Context)) {
            self.callback.replace(callback);
        }

        pub fn call_back(&self, context: &mut dyn Context) {
            self.callback.map(|callback| callback(context));
        }
    }
}

use call_back::CallBack;
use dyn_context::{Context, ContextExt};
use macro_attr_2018::macro_attr;
use std::convert::Into;

macro_attr! {
    #[derive(Context!)]
    struct PrintContext {
         value: String
    }
}

let mut call_back = CallBack::new();
call_back.set_callback(|context| {
    let print: &PrintContext = context.get();
    println!("{}", &print.value);
});
call_back.call_back(&mut PrintContext { value: "Hello, world!".into() });

For using &str instead of String the free_lifetimes! macro can be used:

use dyn_context::{free_lifetimes, Context, ContextExt};
use call_back::CallBack;

free_lifetimes! {
    struct PrintContext {
        value: 'value ref str
    }
}
 
Context!(() struct PrintContext { .. });

let mut call_back = CallBack::new();
call_back.set_callback(|context| {
    let print: &PrintContext = context.get();
    println!("{}", print.value());
});
PrintContextBuilder {
    value: "Hello, world!"
}.build_and_then(|context| call_back.call_back(context));

Because the free_lifetimes! macro cannot be used simultaneously with macro_attr!, the Context! macro deriving Context trait implementation used here in standalone mode.

Required methods

Borrows shareable data entry.

Prefer high-level get wrap.

Borrows mutable data entry.

Prefer high-level get_mut wrap.

Trait Implementations

Merges two contexts into one and calls provided function with the combined context.

Merges two contexts into one and calls provided function with the combined context.

Implementors