3 ms·
> Typing of the .unwrap() makes me acknowledge it could be None. You know, the effect "Oh crap, I better handle that too, right?". It forces me to fix my mental
by millstone 9y ago
> Typing of the .unwrap() makes me acknowledge it could be None. You know, the effect "Oh crap, I better handle that too, right?". It forces me to fix my mental model, and not write the bug, instead of fixing the bug later on.
How does this work for Mutex::lock()? Do you actually try to handle the case where taking the lock fails, because it has been poisoned?
- therein 9y agoFrom the documentation [0] for Mutex<T>: For a mutex, this means that the lock and try_lock methods return a Result which indicates whether a mutex has been poisoned or not. Most usage of a mutex will simply unwrap() these results, propagating panics among threads to ensure that a possibly invalid invariant is not witnessed. A poisoned mutex, however, does not prevent all access to the underlying data. The PoisonError type has an into_inner method which will return the guard that would have otherwise been returned on a successful lock. This allows access to the data, despite the lock being poisoned. [0] https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html https://doc.rust-lang.org/stable/std/sync/struct.Mutex.html
- millstone 9y agoThe author argues that explicit unwrap() is good because it forces you to realize the value may be empty and think "Oh crap, I better handle that too." But the docs you linked say that "most usage of a mutex will simply unwrap these results" and not try to handle the case. So it seems like the explicit unwrap() here is not preventing any bugs, it's just adding noise. Wouldn't automatic unwrap be better, at least in this case?
- iknowstuff 9y agoAgain, it makes the programmer aware of possible issues and gives them a nudge to consider handling the error. This is very valuable.
- the_mitsuhiko 9y agoI personally switched to the parking lot crate which has mutexes that do not poison. I have never seen people need poisoning or handle it.