Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazy_static #39

Open
NN-Binary opened this issue Jul 10, 2019 · 1 comment
Open

lazy_static #39

NN-Binary opened this issue Jul 10, 2019 · 1 comment

Comments

@NN-Binary
Copy link

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
Copy link
Owner

jeromefroe commented Jul 10, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants