Skip to content

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

Closed
@Kmeakin

Description

@Kmeakin

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))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions