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

Warn on SplitN with a count of 1 #7245

Closed
mibes404 opened this issue May 19, 2021 · 2 comments · Fixed by #7292
Closed

Warn on SplitN with a count of 1 #7245

mibes404 opened this issue May 19, 2021 · 2 comments · Fixed by #7292
Labels
A-lint Area: New lints good-first-issue These issues are a good way to get started with Clippy

Comments

@mibes404
Copy link

mibes404 commented May 19, 2021

What it does

It warns the user when SplitN is used where n == 1, specifically when used in combination with .next(). When used in this way, splitn is not doing anything and can be omitted altogether. It is more likely that the user meant to only get the first part after splitting, which means n has to be at least 2.

Categories (optional)

  • Kind: clippy::correctness

What is the advantage of the recommended code over the original code

In the most likely case it will point the user to undesired behaviour, in the other case - where the written code is actually the user's intent - it will make the code more concise.

Drawbacks

None.

Example

fn main() {
   let slice = [10, 40, 30, 20, 60, 50];
   let iter = slice.splitn(1, |num| *num % 3 == 0).next();
   println!("{:?}", iter);
}

Output:

Some([10, 40, 30, 20, 60, 50])

Could be written as:

fn main() {
   let slice = [10, 40, 30, 20, 60, 50];
   let iter = Some(slice);
   println!("{:?}", iter);
}

Output:

Some([10, 40, 30, 20, 60, 50])

Should (most likely) be written as:

fn main() {
   let slice = [10, 40, 30, 20, 60, 50];
   let iter = slice.splitn(2, |num| *num % 3 == 0).next();
   println!("{:?}", iter);
}

Output:

Some([10, 40])
@mibes404 mibes404 added the A-lint Area: New lints label May 19, 2021
@camsteffen camsteffen added the good-first-issue These issues are a good way to get started with Clippy label May 19, 2021
@camsteffen
Copy link
Contributor

Should lint splitn(0, .. too.

@Rustin170506

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints good-first-issue These issues are a good way to get started with Clippy
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants