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

suggest filter, map instead of if let Some(..) { Some() } else { None } on Options? #10078

Open
matthiaskrgr opened this issue Dec 14, 2022 · 0 comments
Labels
A-lint Area: New lints

Comments

@matthiaskrgr
Copy link
Member

matthiaskrgr commented Dec 14, 2022

What it does

I was looking at some rustc code and noticed some if let Some(..) code where we would map back to Some(x) or None in the end and wondered if it would make sense to use filter and map here instead

Lint Name

not sure

Category

pedantic

Advantage

Code is shorter but I am not sure if its easier to understand

Drawbacks

Not sure if readability is actually improved.

Example

fn main() {
    let s = String::from("opt-level=2");
    let i = 42; // whatever

    let z = if let Some("opt-level") = s.split('=').next() { Some(i) } else { None };
    dbg!(z);
}

Could be written as:

fn main() {
    let s = String::from("opt-level=2");
    let i = 42; // whatever

    let z = s.split('=').next().filter(|x| x == &"opt-level").map(|x| i);
    dbg!(z);
}

(we have an Option here so we can filter to None instead of if let .. else { None } and we can map(|x| i) instead of if let .. { Some(i) })

I think the second example looks a bit more streamlined and might be easier to understand it doesn't have all the if let else control flow, on the other hand, the explicit control flow might make the code better to understand as well (explicit is better than implicit etc..)

@matthiaskrgr matthiaskrgr added the A-lint Area: New lints label Dec 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

1 participant