Let's say we have declared an immutable (not let mut
) RwLock
instance like:
let value = RwLock::new(0);
Because the value
is immutable, I expected that I can not change the inner value of the RwLock
. However when I tested, apparently this works:
{
*value.write().unwrap() = 5;
}
I am wondering if I used RwLock
in a wrong way, that this should not have happened (I am worried that the lock might not actually function as expected, if this is the case). However, I am sure there's some explanation behind this behavior since Rust is very explicit when it comes to what you can change and what not.
My guess is the RwLock
stores its inner value on the heap so it only needs to keep track of an immutable pointer to the value. So, whenever we write to the value the RwLock
struct itself would be kept untouched since the pointer wouldn't change.
This is just a guess, and probably a wrong one. I am more than happy if someone would like to correct me.
For clarification: I know how Reader-Writer locks are supposed to work. My question is not about the synchronization mechanism, but rather why doesn't Rust treat RwLock
values like any other value when it comes to immutability. Like is it one of the "magic" types that compiler treats differently, or there's something else I am not aware of.