rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.84k stars 352 forks source link

Incompatible definition of Mutex::lock (or MutexGuard) #393

Open Nahor opened 3 months ago

Nahor commented 3 months ago
struct MutexGuard<'a, T: 'a> {
    data: &'a T,
    //..
}

// Locking the mutex is explicit.
impl<T> Mutex<T> {
    fn lock(&self) -> MutexGuard<T> {
        // Lock the underlying OS mutex.
        //..

        // MutexGuard keeps a reference to self
        MutexGuard {
            data: self,
            //..
        }
    }
}

Some of the code implies that MutexGuard references Mutex, but some other places imply that MutexGuard references T directly. I believe the correct definition of MutexGuard ^1 is

  struct MutexGuard<'a, T: 'a> {
    data: &'a Mutex<T>,
    //..
  }

And if MutexGuard contains a reference to Mutex rather than T, then the Deref implementation needs to be corrected as well.

define lock as fn lock(&self) -> MutexGuard<Mutex<T>> or change the creation of the MutexGuard to MutexGuard { data: self.<unnamed field for now, ... }