Can I mark an immutable borrow as exclusive in Rust?

Viewed 90

I have a data structure, that is somewhat like a RwLock. It is not re-entrant, but the actual locking mechanism is a const function. Is there any way that I can mark this function as "exclusive_borrow" without switching it to be be a mutable function. That way multiple calls to 'read' will be caught at compile time instead of panicking.

struct MyRwLock<T> {
  t: T,
}

impl MyRwLock {
  // Works fine, but doesn't enforce on compile time that there is 
  // only 1 Guard.
  pub fn read(&self) -> ReadGuard<'_, T> { ... }

  // Enforces only 1 ReadGuard at compile time, but unnecessarily 
  // requires MyMutex to be mutable to read.
  pub fn mut_read(&mut self) -> ReadGuard<'_, T> { ... }
}
1 Answers

&mut is a bit of a misnomer. It actually means exclusive reference, not mutable. If that's what you want, then it's correct to use &mut.

In fact, there was a proposal to rename &mut back in 2014. It never came through, but you might occasionally hear whispers of the "mutpocalypse" today.

Related