Thread with 9 posts

jump to expanded post

When I need to find a minimum time, minimum screen co-ordinate, etc, I often find myself writing Rust code like this:

if let Some(new) = new {
    current = Some(current.map(|i| i.min(new)).unwrap_or(new));
}

Is there a better way to do this? Even if it just covers the inner part (the case where new.is_some()), I’d love to know.

Open thread at this post

neatest solution so far comes courtesy https://twitter.com/LambdaFairy/status/1625114170504118272

knowing Ord::max() does what we want for an Option, but Ord::min() doesn’t, then if we define an enum exactly like Option but with the variants in the reverse order, we get an enum for which Ord::min() will do the right thing (but Ord::max() doesn’t)

with that said… you should probably just use match (a, b) { and handle all four cases :p

Open thread at this post
NeoRaider , @neoraider@chaos.social
(open profile)

@hikari Two options I can think of:
- match (current, new) { ... } and handle all Some/None combinations explicitly. Offers the best readability IMO, and results in the shortest machine code of all variants I checked.
- [current, new].into_iter().flatten().min(); Requires the workaround described in the Iterator::min() docs for floats though... and generates absolutely atrocious code.

Open remote post (opens in a new window)