rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.33k stars 1.53k forks source link

Rule: `option_map_or_else_none_and_some` #13303

Open tvolk131 opened 1 month ago

tvolk131 commented 1 month ago

What it does

Very similar to the option_map_or_none rule.

When calling map_or_else() on an Option<T> and the following two conditions are met:

This is effectively a more verbose way of doing what Option::map() does.

Advantage

Code is shorter, more expressive, and more concise.

Drawbacks

Given that this rule is only applicable within such narrow constraints, I don't think there is any downside.

Example

Some(1).map_or_else(|| None, |num| Some(num + 1))

Could both be written as:

Some(1).map(|num| num + 1)
nyurik commented 1 month ago

while similar to option_map_or_none, this lint would need to modify lambda code, which I would think is slightly trickier:

In other words, there would need to be code evaluating every code path inside the lambda to check that every one either returns Some(...) or ! (i.e. panics)

tvolk131 commented 1 month ago

this lint would need to modify lambda code

Good point! I was thinking solely of lambdas that immediately return None or Some, but the examples you listed would be nice to tackle too. I imagine the simple case could be done first, and the cases you mentioned could be added later.