Hacker News new | past | comments | ask | show | jobs | submit login

I am slightly confused about why the MutexGuard type is required in the locking example. Why can locking a lock not just return &mut? The API as written does so eventually anyway, through access(). I guess the API as written allows you to call access() multiple times, but I do not see how this is a useful property if the mutex stays locked for the entire scope of the MutexGuard anyway.



The key is that the MutexGuard is responsible for unlocking (and it does so automatically on destruction). That way, you're tying the scope for the &mut reference to the scope in which the lock is actually held.


Similarly, I quite don't understand what in the type signatures precisely tie MutexGuard to the result of access.

Like, in the "Disaster averted" example the mutex section, how is it detecting that "error: `guard` does not live long enough"? I see that access returns a borrowed mutable T. But, how does the compiler know that that's borrowed from guard instead of a hypothetical second or third parameter or from some other (global?) state altogether?

Edit: Or maybe if a function returns a borrow, then the borrow cannot outlive the scope of the function?


What's going on here is a bit of shorthand. If you don't use the shorthand, the signature looks like:

    fn access<'a, T: Send>(guard: &'a mut MutexGuard<T>) -> &'a mut T;
This says that the incoming borrow and the returned borrows have identical scopes (officially called "lifetimes" in Rust; 'a here is a lifetime variable.) It's a very typical pattern: if you return some borrowed data, it generally comes from a borrow you were given, and the shorthand allows you to leave this implicit in cases where it's clear.

EDIT FOR CLARITY: in particular, you're saying that if you take a "sublease" from something you've already borrowed, that sublease is valid for no longer than the original lease. So for example if you borrow a field out of a borrowed structure, the access to the field can last no longer than you had access to the original structure. In this case, we're saying that access to the data lasts no longer than the lock is held.

I'd recommend http://blog.skylight.io/rust-means-never-having-to-close-a-s... if you want to get a bit more of a feel for how this works.

The details about the shorthand are here: https://github.com/rust-lang/rfcs/pull/141


I take it there's no way of tying the lifetime of the MutexGuard to the lifetime of the .access return, so that you don't have to have this intermediate step?


The version presented in the blog post is simplified. In actual Rust, you don't need to write .access, as it is elided using the Deref trait. So in practice there isn't an intermediate step.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: