Does dereffing past a RwLockReadGuard immediately drop the guard?

/// The default manager for handling the list of users stored locally. It also allows for user creation, and is used especially
/// for when creating a new user via the registration service
pub struct AccountManagerInner {
    local_nac: NetworkAccount,
    cnacs: HashMap<u64, ClientNetworkAccount>

pub struct AccountManager {
    inner: Arc<RwLock<AccountManagerInner>>

impl Deref for AccountManager {
    type Target = AccountManagerInner; // How about RwLockReadGuard<'a, AccountManagerInner>?
    fn deref(&self) -> &Self::Target {
        &* // Deref happens here with the &*
        // If I just return, then I return a RwLockReadGuard<'a, AccountManagerInner>. But, this doesn't work because we need to pass a reference thereto. The struct gets created and then immediantly dropped, which invalidated the reference

Is returning a deref'd RwLockReadGuard<'a, AccountManagerInner> wise? Does dereffing it drop the guard? If not, then how does the program know that a borrow still exists?

Yes, the guard will be dropped at the end of the scope, and that reference will be invalidated. You cannot implement Deref to look into RwLock and friends.

1 Like

I'm pretty sure this won't compile, for precisely the reasons that the OP is concerned about. Thus, the question is moot.

Yeah, I just tried in in the playground and it doesn't compile. Okay. So, if this was a type in your program that you needed distributed throughout, and 99% of the time you were just going to read into it, is there an optimal design pattern that you're aware of for thread-safe multiple access? Or, should I stick with the current design of Arc+RwLock, and then only read and write within the closure that I need to?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.