Hacker News new | ask | show | jobs
by brundolf 2001 days 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.
1 comments

(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.)