Returning a RWLockReadGuard independently from a method

前端 未结 1 713
死守一世寂寞
死守一世寂寞 2020-12-11 07:04

I have an object of type

Arc>

And I have a method that is supposed to take some kind of reference to

相关标签:
1条回答
  • 2020-12-11 07:21

    As described in Why can't I store a value and a reference to that value in the same struct?, the Rental crate allows for self-referential structs in certain cases.

    #[macro_use]
    extern crate rental;
    
    use std::sync::{Arc, RwLock};
    
    struct SessionData;
    impl SessionData {
        fn hello(&self) -> u8 { 42 }
    }
    
    rental! {
        mod owning_lock {
            use std::sync::{Arc, RwLock, RwLockReadGuard};
    
            #[rental(deref_suffix)]
            pub struct OwningReadGuard<T>
            where
                T: 'static,
            {
                lock: Arc<RwLock<T>>,
                guard: RwLockReadGuard<'lock, T>,
            }
        }
    }
    
    use owning_lock::OwningReadGuard;
    
    fn owning_lock(session: Arc<RwLock<SessionData>>) -> OwningReadGuard<SessionData> {
        OwningReadGuard::new(session, |s| s.read().unwrap())
    }
    
    fn main() {
        let session = Arc::new(RwLock::new(SessionData));
    
        let lock = owning_lock(session.clone());
        println!("{}", lock.hello());
    
        assert!(session.try_read().is_ok());
        assert!(session.try_write().is_err());
    
        drop(lock);
    
        assert!(session.try_write().is_ok());
    }
    

    See also:

    • How to return a reference to a sub-value of a value that is under a mutex?
    • Returning the T borrowed from RefCell<T>
    • Why can't I store a value and a reference to that value in the same struct?
    0 讨论(0)
提交回复
热议问题