memoryrustlazy-static

How do I free memory in a lazy_static?


The documentation states that if the type has a destructor, it won't be called: https://docs.rs/lazy_static/1.4.0/lazy_static/#semantics

So how am I supposed to free the memory?


Solution

  • So how am I supposed to free the memory?

    Make your lazy_static an Option, and call take() to free the memory once you no longer need it. For example:

    lazy_static! {
        static ref LARGE: Mutex<Option<String>> =
            Mutex::new(Some(iter::repeat('x').take(1_000_000).collect()));
    }
    
    fn main() {
        println!("using the string: {}", LARGE.lock().as_ref().unwrap().len());
        LARGE.lock().take();
        println!("string freed")
        assert!(LARGE.lock().is_none());
    }
    

    Playground

    As others have pointed out, it is not necessary to do this kind of thing in most cases, as the point of most global variables is to last until the end of the program, at which case the memory will be reclaimed by the OS even if the destructor never runs.

    The above can be useful if the global variable is associated with resources which you no longer need past a certain point in the program.