Changing value behind shared ref

Hi all,

I have this snippet here which bases on this article.

Could anybody explain me why this compiles?

What bothers me is this:

fn mutate_string(&self) {
    *self.mutex.lock().unwrap() = "surprise!".to_owned();
}

Why is this assignment possible when it's behind a shared ref?

Regards
keks

Rust does have shared mutability, often called interior mutability, which allows mutation through a shared reference. Here's some documentation on the topic. Getting used to this concept can be easier, in my opinion, if you mentally substitute some phrases:

When you read Think of it as
Mutable reference Exclusive reference
Immutable reference Shared reference
Interior mutability Shared mutability

This shared mutability lies behind the concurrency types which allow you to get a &mut, like Mutex and RwLock in addition to the Cell types and Atomic types. It's also implicitly present in other places, like when you allocate something with a clone or write through a &File.

3 Likes

I wrote about this topic a few years ago: Temporarily opt-in to shared mutation – Alice Ryhl

2 Likes

Ahhh right! :slight_smile: Now I remember a video I've seen from Jon Gjengset on YouTube where he said that you can count Mutex also as one of those types! Anyways: Thank you very much for your kind help folks! :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.