4 ms·
What about all the `unwraps`? I have nightmares from last time I tried to get into Rust and it was unwrapping everything all the way down.
by speg 11y ago
What about all the `unwraps`? I have nightmares from last time I tried to get into Rust and it was unwrapping everything all the way down.
- vbezhenar 11y agoYou should handle errors, not unwrap them.
- danieldk 11y agoHandle errors, or use try! when you want to propagate errors to the caller: https://doc.rust-lang.org/std/macro.try!.html https://doc.rust-lang.org/std/macro.try!.html
- burntsushi 11y agoThe book has a section on error handling, starting with the basics: https://doc.rust-lang.org/book/error-handling.html https://doc.rust-lang.org/book/error-handling.html
- sanderjd 11y agoThe only violator I found in these exercises is the one that uses mutexes. The suggested answer involves `val.lock().unwrap()`, which is (anecdotally) common in real Rust code. An error result of a mutex unlock implies that another thread panicked while holding the lock[0], so propagating that panic is likely the right answer in this case. [0]: https://doc.rust-lang.org/std/sync/struct.Mutex.html#poisoning https://doc.rust-lang.org/std/sync/struct.Mutex.html#poisoni...
- lhnz 11y agoOften the quickest replacement for an `unwrap` is an `unwrap_or` with a sensible default. Other times where error-handling is important use a `match` there and then. And don't nest the arms of the match instead use the return of the match expression. On the other hand, I found `try!` pretty awkward. Especially since quite often you need to create custom errors alongside it and can go down a rabbit hole in which you have to read confusing compiler messages from within macros about traits not being implemented correctly, and lifetimes missing, etc.