Conventions for avoiding surprises with interior mutability?
⚓ Rust 📅 2025-10-28 👤 surdeus 👁️ 5Hi Rust experts. I am writing some code that is fairly heavily multi-threaded, and as a result have many Sync/Send structs with methods with a (&self, ...) signature (rather than (&mut self, ...)) that mutate their state internally using RwLocks, Atomics, Mutexes, etc.
One thing that has been difficult for me to reason about is how to avoid logical "surprises" wrt interior mutability. For example, it is very easy for me to reason about a method like fn increment(&mut self) and understand that it mutates state and has side-effects, but less so with a method like fn increment(&self) that does so with (necessary) interior mutability and thus has side-effects when one might infer that it is pure, aside from the naming obviously.
I know that good naming and docs can help mitigate this surprise factor, but are there other ways? Are there good guidelines in some well established crates?
If anyone could point me to some "best practices" in this area or even share some ideas on how to manage it, I would appreciate it.
2 posts - 2 participants
🏷️ Rust_feed