3 ms·
Here's how you can do global mutable state in Rust: #[macro_use] extern crate lazy_static; use std::sync::Mutex; lazy_static! { static ref ARRAY:
by brundolf 6y ago
Here's how you can do global mutable state in Rust:
#[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());
}
I agree that this isn't the most ergonomic, but like most unergonomic things in Rust, there are reasons for it being so.
- steveklabnik 6y ago(You'd probably replace the first two lines with "use lazy_static::lazy_static;" in today's Rust, that older style isn't as idiomatic.)