Designing a type MutexGuardRef<Option<Box<T>>> that derefs to `&Option<&T>`

I'm trying to design a type that stores a MutexGuard for an Option<Box<T>> that I can deref to Option<&T>

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

pub struct MutexGuardRef<'a, T> {
    mutex_guard: MutexGuard<'a, Option<Box<T>>>

impl<'a, T> std::ops::Deref for MutexGuardRef<'a, Option<Box<T>>> {
    type Target = Option<&'a mut T>;

    fn deref(&self) -> &Self::Target {
        &match self.mutex_guard.deref() {
            Some(b) => b,
            None => None

but I get this error:


error[E0308]: mismatched types
  --> src/
13 |             Some(b) => b,
   |                        ^ expected enum `Option`, found reference
   = note:   expected enum `Option<&mut T>`
           found reference `&Box<Option<Box<T>>>`

Which does not make sense. When I call self.mutex_guard.deref(), since the internal type of MutexGuardRef is Option<Box<T>>, this should deref to &Option<Box<T>> and thus matching on it should give me either &Box<T> or None, but it's giving me Box<Option<Box<T>>>. What is happening?

You're implementing for MutexGuardRef<'a, Option<Box<T>>>. Let's say U = Option<Box<T>>, then we can say you're implementing for MutextGuardRef<'a, U>.

That means self.mutex_guard is a MutexGuard<'a, Option<Box<U>>> as per your struct definition. Expanding U back out, we see that it's a MutexGuard<'a, Option<Box<Option<Box<T>>>>>.


impl<'a, T> std::ops::Deref for MutexGuardRef<'a, T> {

Or maybe changing the definition of your struct, I'm not sure what you want.

(There are some further errors after correcting this one which I have not followed up on.)

1 Like

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.