WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 34 of 100

How do you use the lazy_static crate in Rust, and what problem does it solve?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

The ‘lazy_static‘ crate in Rust allows you to create global variables that are initialized lazily, i.e., only when they are first accessed. This crate solves the problem of initialization order, which is important for Rust’s memory safety guarantees.

Here’s an example of using ‘lazy_static‘:

    #[macro_use]
    extern crate lazy_static;
    
    use std::collections::HashMap;
    
    lazy_static! {
        static ref MY_MAP: HashMap<i32, &'static str> = {
            let mut map = HashMap::new();
            map.insert(0, "zero");
            map.insert(1, "one");
            map.insert(2, "two");
            map
        };
    }
    
    fn main() {
        println!("{}", MY_MAP.get(&1).unwrap());
    }

In this example, we define a global ‘HashMap‘ called ‘MY_MAP‘, which is initialized lazily using a closure. The closure is only executed the first time ‘MY_MAP‘ is accessed.

When you run this program, you’ll see "one" printed to the console. This is because we accessed the value associated with the key ‘1‘, which was lazily initialized when the program first accessed ‘MY_MAP‘.

One important thing to note is that ‘lazy_static‘ uses synchronization primitives to ensure that initialization is thread-safe. This means that even if multiple threads are trying to access ‘MY_MAP‘ at the same time, the initialization closure will only be executed once.

In summary, the ‘lazy_static‘ crate in Rust allows you to define global variables that are initialized lazily, solving the problem of initialization order and providing thread-safe access to shared resources.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics