rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Suggest to replace `Option.into_iter().filter_map(func).next()` with `Option.and_then(func)`

Open bnjbvr opened this issue 1 year ago • 3 comments

What it does

Somehow I always want to use filter_map with Option, and I always forget that it's equivalent to Option::and_then, so I end up doing this contrived way that uses a few functions. This lint would remind me that and_then exists and could and should be used in this case.

Advantage

Remove two intermediate function calls, with the complexity they entail, and use a more idiomatic Rust way.

Drawbacks

Maybe too targeted to my brain's dysfunctions 🤪

Example

let a_value = Some(42);
let x = a_value.into_iter().filter_map(|value| if value < 30 { Some(value + 13) } else { None }).next();

Could be written as:

let a_value = Some(42);
let x = a_value.and_then(|value| if value < 30 { Some(value + 13) } else { None });

bnjbvr avatar Oct 02 '24 16:10 bnjbvr