Reputation: 4912
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
?
Upvotes: 1
Views: 452
Reputation: 43743
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.
Upvotes: 4