Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It seems Rust's unwrap is the exact opposite of ?? "". It throws an error instead of using a fallback value, which is exactly what the author suggests instead of using ?? "".


Author here. I believe I did a poor job of explaining what I meant by this sentence in the article. Sorry about that.

As you, and many others, have pointed out, `?? ""` does not do what `.unwrap` does. `unwrap_or_default` would have been a better comparison for what it actually does. What I tried, and failed, to communicate, was that both can be used to "ignore" the unwanted state, `None` or `undefined`.

I guess the rust equivalent to what I would like to see is `nullable_var?`, and not unwrap as that will panic. That would be equivalent to the `?? throw new Error` feature mentioned further up in the comments.


From the article:

> In Rust, however, you're forced to reason about the "seriousness" of calling .unwrap() as it could terminate your program. In TS you're not faced with the same consequences.


Yes that was a mistake.

unwrap() is the error.

unwrap_or() is the fallback.


Also unwrap_or_default() which is useful in many cases. For example the default for a string is empty string, default for integers is 0 and default for bool is false.

For your own types you can implement the Default trait to tell Rust what the default value is for that type.




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

Search: