Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option::map(_).flatten() => Option::and_then(_) #5175

Closed
lopopolo opened this issue Feb 14, 2020 · 4 comments · Fixed by #5473
Closed

Option::map(_).flatten() => Option::and_then(_) #5175

lopopolo opened this issue Feb 14, 2020 · 4 comments · Fixed by #5473
Labels
C-enhancement Category: Enhancement of lints, like adding more cases or adding help messages good-first-issue These issues are a good way to get started with Clippy L-complexity Lint: Belongs in the complexity lint group

Comments

@lopopolo
Copy link

The map_flatten lint seems to only apply to iterators:

declare_clippy_lint! {
/// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
///
/// **Why is this bad?** Readability, this can be written more concisely as a
/// single method call.
///
/// **Known problems:**
///
/// **Example:**
/// ```rust
/// let vec = vec![vec![1]];
/// vec.iter().map(|x| x.iter()).flatten();
/// ```
pub MAP_FLATTEN,
pedantic,
"using combinations of `flatten` and `map` which can usually be written as a single method call"
}

For Option, map + flatten can be replaced with and_then.

see for example this code:

captures.get(index).map(Option::as_deref).flatten()

which can be more succinctly written as:

captures.get(index).and_then(Option::as_deref)
@flip1995
Copy link
Member

flip1995 commented Feb 14, 2020

This is only the case, when get(..) returns an Option<Option<_>> type, right?

Wait flatten is only implemented for Option<Option<T>>, so it would type error if map would return something other than Option<Option<_>> anyway.

@flip1995 flip1995 added L-complexity Lint: Belongs in the complexity lint group good-first-issue These issues are a good way to get started with Clippy C-enhancement Category: Enhancement of lints, like adding more cases or adding help messages labels Feb 14, 2020
@lopopolo
Copy link
Author

In this case get returns an Option<&Option<Vec<u8>>>

@marcin-serwin
Copy link
Contributor

Hi, Could I take a look at this issue?

@flip1995
Copy link
Member

Sure, go ahead!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-enhancement Category: Enhancement of lints, like adding more cases or adding help messages good-first-issue These issues are a good way to get started with Clippy L-complexity Lint: Belongs in the complexity lint group
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants