[−][src]Crate lazy_st
Single-threaded lazy evaluation.
Lazy evaluation allows you to define computations whose evaluation is deferred to when they are actually needed. This can be also achieved with closures; however, in case of lazy evaluation, the output of computations is calculated only once and stored in a cache.
Lazy evaluation is useful if you have an expensive computation of which you might need the result more than once during runtime, but you do not know in advance whether you will need it at all.
Let us consider an example, where we first use a closure to defer evaluation:
fn expensive() -> i32 { println!("I am expensive to evaluate!"); 7 } fn main() { let a = || expensive(); // Nothing is printed. assert_eq!(a(), 7); // "I am expensive to evaluate!" is printed here let b = [a(), a()]; // "I am expensive to evaluate!" is printed twice assert_eq!(b, [7, 7]); }
Contrast this with using lazy evaluation:
fn expensive() -> i32 { println!("I am expensive to evaluate!"); 7 } fn main() { let a = lazy!(expensive()); // Nothing is printed. // Thunks are just smart pointers! assert_eq!(*a, 7); // "I am expensive to evaluate!" is printed here let b = [*a, *a]; // Nothing is printed. assert_eq!(b, [7, 7]); }
Lazy values from this crate cannot be shared between threads.
If you need this, please consider using the lazy-mt
crate.
Macros
lazy | Construct a lazily evaluated value using a closure. |
Structs
Thunk | A lazily evaluated value. |
Traits
Evaluate | Generalisation of lazy evaluation to other types than closures. |
Type Definitions
Lazy | A lazily evaluated value produced from a closure. |