622
submitted 10 months ago by jroid8@lemmy.world to c/programmerhumor@lemmy.ml
you are viewing a single comment's thread
view the rest of the comments
[-] mea_rah@lemmy.world 3 points 10 months ago* (last edited 10 months ago)

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 like 0 that would be a better example and honestly make more sense there.

let parsed_numbers = ["1", "not a number", "3"]
    .iter()
    .map(|n| n.parse().unwrap_or(0))
    .collect();

// prints "[1, 0, 3]"
println!("{:?}", parsed_numbers);

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:

maybe_number.unwrap_or(0)

Or perhaps more idiomatic version of the above:

maybe_number.unwrap_or_default()
[-] words_number@programming.dev 2 points 10 months ago

I think you could even get rid of the iter() and the collect() since it's a small fixed size array.

this post was submitted on 08 Dec 2023
622 points (96.4% liked)

Programmer Humor

32271 readers
173 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS