rustthread-safetyglobal-variableslazy-static

How to mutate static ref usize?


lazy_static! {
  static ref MY_GLOBAL: Mutex<usize> = Mutex::new(100);
}
MY_GLOBAL.lock().unwrap() += 1;

This code gives me these errors:

cannot use `+=` on type `MutexGuard<'_, usize>`
cannot assign to this expression

How do I mutate MY_GLOBAL?


Solution

  • Your code needs just one *:

    *MY_GLOBAL.lock().unwrap() += 1;
    

    The result of MY_GLOBAL.lock().unwrap() is a MutexGuard<'_, usize>, as the compiler noted, which dereferences to a usize, so to modify the containing usize you need a dereference *.

    Rust often automatically inserts referencing and dereferencing when needed (particularly for method calls) but for an assignment you must explicitly dereference so that the left side is exactly the usize you intend to replace.