Unlocking mutex won't return `MutexGuard`

On the code below:

use std::sync::{Arc, Mutex, MutexGuard};
use std::sync::{LockResult, PoisonError};

pub struct MutexGuardOptionRef<'a, T: ?Sized> {
    pub mutex_guard: MutexGuard<'a, Option<Box<T>>>,
}

pub trait LockableOption<T: ?Sized> {
    fn lock(&self) -> LockResult<MutexGuardOptionRef<T>>;
}

pub type LockableArc<T> = Arc<Mutex<Option<T>>>;

impl<T> LockableOption<T> for LockableArc<Box<T>> {
    fn lock(&self) -> LockResult<MutexGuardOptionRef<T>> {
        let mutex_guard = self.lock();
        match mutex_guard {
            Ok(m) => Ok(MutexGuardOptionRef{
                mutex_guard: m
            }),
            _ => unimplemented!()
        }
    }
}

Playground

we have

impl<T> LockableOption<T> for LockableArc<Box<T>> {
    fn lock(&self) -> LockResult<MutexGuardOptionRef<T>> {

since we're implementing for LockableArc<Box<T>>, then self: LockableArc<Box<T>>, so calling self.lock() would call LobkcableArc::lock which is Mutex::lock which should give MutexGuard, but it's saying it gives MutexGuardOptionRef:

Error:

error[E0308]: mismatched types
  --> src/lib.rs:19:30
   |
19 |                 mutex_guard: m
   |                              ^ expected struct `MutexGuard`, found struct `MutexGuardOptionRef`
   |
   = note: expected struct `MutexGuard<'_, Option<Box<T>>>`
              found struct `MutexGuardOptionRef<'_, T>`

What is happening?

In self.lock(), you're recursively referring to LockableOption::lock(). It has precedence over Mutex::lock(). You need to specify the type:

let mutex_guard = Mutex::lock(self);

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.