|
1 | 1 | lazy-static.rs
|
2 | 2 | ==============
|
3 | 3 |
|
4 |
| -A small Rust syntax extension for defining lazy evaluated static variables. |
| 4 | +A macro for declaring lazily evaluated statics in Rust. |
| 5 | + |
| 6 | +Using this macro, it is possible to have `static`s that require code to be |
| 7 | +executed at runtime in order to be initialized. |
| 8 | +This includes anything requiring heap allocations, like vectors or hash maps, |
| 9 | +as well as anything that requires function calls to be computed. |
| 10 | + |
| 11 | +# Syntax |
| 12 | + |
| 13 | +``` |
| 14 | +lazy_static! { |
| 15 | + static ref NAME_1: TYPE_1 = EXPR_1; |
| 16 | + static ref NAME_2: TYPE_2 = EXPR_2; |
| 17 | + ... |
| 18 | + static ref NAME_N: TYPE_N = EXPR_N; |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +# Semantic |
| 23 | + |
| 24 | +For a given `static ref NAME: TYPE = EXPR;`, the macro generates a |
| 25 | +unique type that implements `Deref<TYPE>` and stores it in a static with name `NAME`. |
| 26 | + |
| 27 | +On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs |
| 28 | +can return a reference to the same object. |
| 29 | + |
| 30 | +Like regular `static mut`s, this macro only works for types that fulfill the `Share` |
| 31 | +trait. |
| 32 | + |
| 33 | +# Example |
| 34 | + |
| 35 | +Using the macro: |
| 36 | + |
| 37 | +```rust |
| 38 | +#![feature(phase)] |
| 39 | + |
| 40 | +#[phase(plugin)] |
| 41 | +extern crate lazy_static; |
| 42 | + |
| 43 | +use std::collections::HashMap; |
| 44 | + |
| 45 | +lazy_static! { |
| 46 | + static ref HASHMAP: HashMap<uint, &'static str> = { |
| 47 | + let mut m = HashMap::new(); |
| 48 | + m.insert(0u, "foo"); |
| 49 | + m.insert(1u, "bar"); |
| 50 | + m.insert(2u, "baz"); |
| 51 | + m |
| 52 | + }; |
| 53 | + static ref COUNT: uint = HASHMAP.len(); |
| 54 | + static ref NUMBER: uint = times_two(21); |
| 55 | +} |
| 56 | + |
| 57 | +fn times_two(n: uint) -> uint { n * 2 } |
| 58 | + |
| 59 | +fn main() { |
| 60 | + println!("The map has {} entries.", *COUNT); |
| 61 | + println!("The entry for `0` is \"{}\".", HASHMAP.get(&0)); |
| 62 | + println!("A expensive calculation on a static results in: {}.", *NUMBER); |
| 63 | +} |
| 64 | +``` |
0 commit comments