3 ms·
Even without the ? sugar I don't see what's so offensive about this; the least little formatting effort produces: let id = node.parent().unwrap()
by topspin 10y ago
Even without the ? sugar I don't see what's so offensive about this; the least little formatting effort produces:
let id = node.parent().unwrap()
.parent().unwrap()
.data_get("id").unwrap()
.parse::<usize>().unwrap();
If there is something horrible about that I don't see it.
- 102030485868 10y agoIt hurts to type sometimes. Typing at work isn't really an issue since I have an ergonomic keyboard, but big side projects can sometimes hurt. ? is far easier and faster to type than .unwrap(). So no, there's nothing horrible that I see, there is something horrible that I feel though.
- oblio 10y ago> If there is something horrible about that I don't see it. Isn't unwrap(): a) boilerplate b) repetitive?
- steveklabnik 10y agoIt's boilerplate in a certain sense. Those are all points where what you've written might not work. Rust makes you deal with possible problems _somehow_. Specifically, this is a replacement for null. If you legitimately don't care, then it can feel boilerplate-y, but it also lets you start by not having to care, and then searching for unwrap and replacing it with better handling. In other words, it's boilerplate here because this particular operation has many possible failure modes, and Rust is pointing those out to you. It's repetitive in this particular instance, but doesn't have to be in general.
- stymaar 10y agoc) a bad practice since it will make your program crash is a node has no parent. if the node always having a parent is a invariant of your application, you should use `expect` with a clear error message when the invariant is broken. if your node can have no parents then you want to handle this case explicitly with a `if let Some(parent) = node.parent() {` pattern.
- deleted 10y ago[deleted]
- ballpointcarrot 10y agoSome people prefer their languages to be more concise, and the safety of the the option objects (and the requirement of the unwrap() calls in the function chain) feels unwieldy. Moreover, as the unwrap() calls could panic if there's no attribute, the more complete handling of it is even longer (match calls and following the successful path). This could be a function to isolate just the attribute you need, but seeing the example as it is presented can be off-putting from people used to scripting languages like ruby/python, which are more concise.
- stymaar 10y agoUnwrap will panic if no parent is found, whereas the `?` operator allows for a clean handling of this situation. Dealing with this case properly without using a single `?`, gets really ugly with a lot of nested if let Some(parent) = node.parent() {