Macro zng_app_context::context_local
source · macro_rules! context_local { ($( $(#[$meta:meta])* $vis:vis static $IDENT:ident : $T:ty = $init:expr; )+) => { ... }; }
Expand description
Declares new app and context local variable.
§Examples
context_local! {
/// A public documented value.
pub static FOO: u8 = 10u8;
// A private value.
static BAR: String = "Into!";
}
§Default Value
All contextual values must have a fallback value that is used when no context is loaded.
The default value is instantiated once per app, the expression can be any static value that converts Into<T>
.
§Usage
After you declare the context local you can use it by loading a contextual value for the duration of a closure call.
context_local! { static FOO: String = "default"; }
fn print_value() {
println!("value is {}!", FOO.get());
}
let _scope = LocalContext::start_app(AppId::new_unique());
let mut value = Some(Arc::new(String::from("other")));
FOO.with_context(&mut value, || {
print!("in context, ");
print_value();
});
print!("out of context, ");
print_value();
The example above prints:
in context, value is other!
out of context, value is default!
See ContextLocal<T>
for more details.