Skip to content

A small macro for defining lazy evaluated static variables in Rust.

License

Notifications You must be signed in to change notification settings

phil-opp/lazy-static-core

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

lazy-static.rs

Travis-CI Status

DON'T USE! Seems to have a bug (tests panic sometimes at access of statics)...

A macro for declaring lazily evaluated statics in Rust that doesn't depend on the standard library.

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

Syntax

lazy_static_core! {
    [pub] static ref NAME_1: TYPE_1 = EXPR_1;
    [pub] static ref NAME_2: TYPE_2 = EXPR_2;
    ...
    [pub] static ref NAME_N: TYPE_N = EXPR_N;
}

Semantic

For a given static ref NAME: TYPE = EXPR;, the macro generates a unique type that implements Deref<TYPE> and stores it in a static with name NAME.

On first deref, EXPR gets evaluated and stored internally, such that all further derefs can return a reference to the same object.

Like regular static muts, this macro only works for types that fulfill the Sync trait.

Example

Using the macro:

#![feature(phase)]

#[phase(plugin)]
extern crate lazy_static_core;

use std::collections::HashMap;

lazy_static_core! {
    static ref HASHMAP: HashMap<uint, &'static str> = {
        let mut m = HashMap::new();
        m.insert(0u, "foo");
        m.insert(1u, "bar");
        m.insert(2u, "baz");
        m
    };
    static ref COUNT: uint = HASHMAP.len();
    static ref NUMBER: uint = times_two(21);
}

fn times_two(n: uint) -> uint { n * 2 }

fn main() {
    println!("The map has {} entries.", *COUNT);
    println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
    println!("A expensive calculation on a static results in: {}.", *NUMBER);
}

About

A small macro for defining lazy evaluated static variables in Rust.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Rust 100.0%