jeromefroe / lru-rs

An implementation of a LRU cache
https://docs.rs/lru/
MIT License
643 stars 106 forks source link

lazy_static #39

Open NN-Binary opened 5 years ago

NN-Binary commented 5 years ago

Hey!

Anyway you can show me how to use this cache with lazy_static? I'd like to access it from multiple threads. A working example would be amazing! Thank you

jeromefroe commented 5 years ago

Here's an example program:

#[macro_use]
extern crate lazy_static;

extern crate lru;

use lru::LruCache;

lazy_static! {
    static ref LRU: LruCache<u32, &'static str> = {
        let mut cache = LruCache::new(2);
        cache.put(0, "foo");
        cache
    };
    static ref COUNT: usize = LRU.len();
}

fn main() {
    println!("The cache has {} entries.", *COUNT);
    println!("The cache contains `0`: \"{}\".", LRU.contains(&0));
}

The catch with lazy_static though is that since the references it creates are static they are therefore immutable, so you won't be able to use most of the cache's methods, for example even get, since they manipulate the internal state of the cache. If you don't need to add elements to the cache I think it would be better to just use a Hashmap. On the other hand, if you do need to update the cache after it's created, then you won't be able to use lazy_static but will need to instead initialize during runtime.