How can I use mutable lazy_static?


#1

I use a large stack for my program, so I tried to use lazy_static.

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref VEC: Vec<i32> = {
        let mut m = Vec::with_capacity(1000);
        m
    };
}

fn main() {
    VEC.push(3);
}

The compiler complains “cannot borrow immutable borrowed content as mutable”.
I tried to insert “mut” in declaration part of VEC and failed.

How can I use mutable lazy_static?


#2

You need a Mutex (https://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html).


#3

Thanks for your hint, I found the following code in Stackoverflow.

#[macro_use]
extern crate lazy_static;

use std::sync::Mutex;

lazy_static! {
    static ref ARRAY: Mutex<Vec<u8>> = Mutex::new(vec![]);
}

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    println!("called {}", ARRAY.lock().unwrap().len());
}

Thank you!