this post was submitted on 08 Dec 2023
622 points (96.4% liked)
Programmer Humor
32483 readers
516 users here now
Post funny things about programming here! (Or just rant about your favourite programming language.)
Rules:
- Posts must be relevant to programming, programmers, or computer science.
- No NSFW content.
- Jokes must be in good taste. No hate speech, bigotry, etc.
founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
There's a nice list of this feature by language on the Wikipedia page for anyone interested: https://en.wikipedia.org/wiki/Null_coalescing_operator#Examples_by_languages
This was my first time actually seeing a Rust example, and I hate it.
Other languages: if a is null return b.
Rust: here is an array of strings, we are going to parse the array to numbers. If that conversion fails we handle the exception and return the minimum integer value. We then save the result in a new vector. We also print it.
I like rust, but I hate the example too. It's needlessly complex. Should have just been a.unwrap_or(b).
The example even used unwrap_or_else where they should use unwrap_or. Then it uses
std::i64::MIN
as fallback value where they could use something like0
that would be a better example and honestly make more sense there.Even without trimming this to something less convoluted, the same functionality (with different fallback value) could be written in more readable form.
Obviously in the context of the page something like this would make way more sense:
Or perhaps more idiomatic version of the above:
I think you could even get rid of the
iter()
and thecollect()
since it's a small fixed size array.