I have an object of type
Arc>
And I have a method that is supposed to take some kind of reference to
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: