How to "Constrain Lifetime Parameter"?

I've got a teeny little program example and I'm trying to figure out how to return an RwLockReadGuard in a Deref implementation ( I know this may not be the best idea but I wanted to play around with it a little bit for fun and experimentation ):

use std::sync::{RwLock, Arc, RwLockReadGuard};

struct Gc<T> {
    data: Arc<RwLock<T>>,
}

impl<T> Gc<T> {
    fn new(data: T) -> Self {
        Gc {
            data: Arc::new(RwLock::new(data))
        }
    }
}

impl<'a, T> std::ops::Deref for Gc<T> {
    type Target = RwLockReadGuard<'a, T>;

    fn deref(&'a self) -> &'a Self::Target {
        self.data.read()
    }
}

fn main() {
    
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:15:6
   |
15 | impl<'a, T> std::ops::Deref for Gc<T> {
   |      ^^ unconstrained lifetime parameter

error: aborting due to previous error

For more information about this error, try `rustc --explain E0207`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Deref isn't suitable for this. It can only return a reference, not a type like RwLockReadGuard that must be returned by ownership (since it has a destructor that runs when its owner goes out of scope). This is why RwLock needs explicit read and write methods instead of just implementing deref and deref_mut.

1 Like

Ah, thanks. That makes sense.

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.