#state #global #scope #stateful #macro #record #variables

macro-stateful

A library to help record state in a global scope

1 unstable release

0.1.0 Dec 25, 2024

#1066 in Rust patterns

Download history 149/week @ 2024-12-24

149 downloads per month

MIT/Apache

4KB
52 lines

Recording state via the global scope variable

Usage:

Using the define_state macro, define the state with a unique name and specify its type. Using set_state to modify the state, the parameter type in the callback is Option<T> where T is the type specified for the state.

use macro_stateful::{define_state, set_state,take_out};

set_state! {UniqueState,|v|{
    let v = v.as_mut().unwrap();
    println!("invoke dynamically 1 times, previous: {:?}",v);
    *v = 1;
}}

set_state! {UniqueState,|v|{
    let v = v.as_mut().unwrap();
    println!("invoke dynamically 2 times, previous: {:?}",v);
    *v = 2;
}}

set_state! {UniqueState,|v|{
    let v = v.as_mut().unwrap();
    println!("invoke dynamically 3 times, previous: {:?}",v);
    *v = 3;
}}

define_state! {UniqueState:i32 = {
    println!("init");
    0
}}

fn main() {
    let r = take_out!(UniqueState);
    println!("{r:?}");
}

Dependencies

~210–650KB
~16K SLoC