[][src]Trait dyn_context::Context

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>; }

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 context! macro can be used:

use dyn_context::{context, ContextExt};
use call_back::CallBack;

context! {
    struct PrintValue {
        value: ref str
    }
}

context! {
    dyn struct PrintContext {
        value: ref PrintValue
    }
}

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

Required methods

fn get_raw(&self, ty: TypeId) -> Option<&dyn Any>

Borrows shareable data entry.

Prefer high-level get wrap.

fn get_mut_raw(&mut self, ty: TypeId) -> Option<&mut dyn Any>

Borrows mutable data entry.

Prefer high-level get_mut wrap.

Loading content...

Implementors

impl Context for ![src]

impl Context for ()[src]

impl Context for ExampleContext[src]

Loading content...