Skip to content

Suggest replacing Iterator::fold with Iterator::try_fold when appropriate #10208

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
Kmeakin opened this issue Jan 18, 2023 · 1 comment · Fixed by #11012
Closed

Suggest replacing Iterator::fold with Iterator::try_fold when appropriate #10208

Kmeakin opened this issue Jan 18, 2023 · 1 comment · Fixed by #11012
Labels
A-lint Area: New lints

Comments

@Kmeakin
Copy link

Kmeakin commented Jan 18, 2023

What it does

Replaces instances of Iterator::fold which replicate the behavior of Iterator::try_fold

Lint Name

manual_try_fold

Category

complexity, perf

Advantage

  • Iterator::try_fold is more efficient, because it terminates early in the Err/None case
  • Outsources error handling to Iterator::try_fold

Drawbacks

  • Iterator::try_fold is newer than Iterator::fold, so may be unfamiliar to some users or not available on projects that want to work on old versions of Rust

Example

fn maybe_sum(xs: &[u32]) -> Option<u32> {
    xs.iter().fold(Some(0), |sum, x| sum?.checked_add(*x))
}

Could be written as:

fn maybe_sum(xs: &[u32]) -> Option<u32> {
    xs.iter().try_fold(0, |sum, x| sum.checked_add(*x))
}
@Houtamelo
Copy link

I believe this lint should be deactivated by default, as there are cases where the suggestion introduces different behavior

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