This Rust crate provides a macro to generate aux macros for on-demand usage.
toml
[dependencies]
on_demand = "0.1"
```rust use ondemand::generateondemandmacro;
fn foo() { generateondemandmacro!(a: usize = None, { println!("a"); 1 }); generateondemandmacro!(b: usize = None, { println!("b"); let adata = ondemandgeta!(); 2 + *adata }); generateondemandmacro!(c: usize = None, { println!("c"); let adata = ondemandgeta!(); let bdata = ondemandgetb!(); 3 + *adata + *bdata });
let c_data = on_demand_get_c!();
assert_eq!(*c_data, 6);
} ```
After calling generate_on_demand_macro
to the variable (for example, a
), three new macros on_demand_get_a
, on_demand_get_a_mut
and on_demand_into_a
are generated. When on_demand_get_a
is called, it determines whether a
has been calculated. If it is, then returns the reference to its data, otherwise calls the expression given as the second parameter of generate_on_demand_macro
, then assigns the returned value to a
. The other two generated macros do the similar job, but returns the mutable reference to, or takes ownership of a
.
In all, this means calculating a
lazily using the expression.