zng_var

Macro when_var

source
macro_rules! when_var {
    ($($tt:tt)*) => { ... };
}
Expand description

Initializes a new conditional var.

A condition var updates when the first true condition changes or the mapped var for the current condition changes.

§Syntax

The macro expects a list of condition-var => condition-value-var, the list is separated by comma. The last condition must be the _ token that maps to the value for when none of the conditions are true.

The condition-var must be an expression that evaluates to an impl Var<bool> type. The condition-value-var must by any type that implements IntoVar. All condition values must be of the same VarValue type.

§Examples

let condition = var(true);
let when_false = var("condition: false".to_txt());

let t = Text!(when_var! {
    condition.clone() => "condition: true".to_txt(),
    _ => when_false.clone(),
});

In the example if condition or when_false are modified the text updates.

§cfg

Every condition can be annotated with attributes, including #[cfg(..)].

let t = Text!(when_var! {
    #[cfg(some_flag)]
    condition0 => "is condition 0".to_txt(),
    #[cfg(not(some_flag))]
    condition1 => "is condition 1".to_txt(),
    _ => "is default".to_txt(),
});

In the example above only one of the conditions will be compiled, the generated variable is the same type as if you had written a single condition.

§Contextualized

The when var is contextualized when needed, meaning if any input is_contextual at the moment the var is created it is also contextual. The full output type of this macro is a BoxedVar<T> that is either an ArcWhenVar<T> or a ContextualizedVar<T, ArcWhenVar<T>>.