1
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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.