Skip to content

clippy could suggest .is_empty() for more things #11212

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

Closed
matthiaskrgr opened this issue Jul 23, 2023 · 2 comments · Fixed by #13421
Closed

clippy could suggest .is_empty() for more things #11212

matthiaskrgr opened this issue Jul 23, 2023 · 2 comments · Fixed by #13421
Labels
A-lint Area: New lints

Comments

@matthiaskrgr
Copy link
Member

matthiaskrgr commented Jul 23, 2023

What it does

https://rust-lang.github.io/rust-clippy/master/index.html#/comparison_to
covers things like string = "", but we could also perhaps catch things like get the first element and check if that's SomeorNone`

        let v: &[i32] = &[1,2,3];
        if let Some(_) = v.get(0) {
                eprintln!("not_empty");
        }
        let v: &[i32] = &[1,2,3];
        if let Some(_) = v.get(0) { // !is_empty()
                eprintln!("not_empty");
        }
        let v: &[i32] = &[1,2,3];
        if let Some(_) = v.first() { // !is_empty()
                eprintln!("not_empty");
        }
        let v: &[i32] = &[1,2,3];
        if  v.get(0).is_some() {
                eprintln!("not_empty");
        }
        let v: &[i32] = &[1,2,3];
        if  v.first().is_some() {
                eprintln!("not_empty");
        }
@matthiaskrgr matthiaskrgr added the A-lint Area: New lints label Jul 23, 2023
@y21
Copy link
Member

y21 commented Jul 23, 2023

I think for all of these cases, clippy already leads you to writing v.first().is_some() through other lints, so maybe it just needs to lint that one case and suggest !v.is_empty()?

@matthiaskrgr
Copy link
Member Author

yeah, exactly

bors added a commit that referenced this issue Sep 19, 2024
Initial impl of `unnecessary_first_then_check`

Fixes #11212

Checks for `{slice/vec/Box<[]>}.first().is_some()` and suggests replacing the unnecessary `Option`-construct with a direct `{slice/...}.is_empty()`. Other lints guide constructs like `if let Some(_) = v.get(0)` into this, which end up as `!v.is_empty()`.

changelog: [`unnecessary_first_then_check`]: Initial implementation
@bors bors closed this as completed in 290a01e Sep 19, 2024
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

Successfully merging a pull request may close this issue.

2 participants