rust-lang / rust-lang/rust-clippy

Clippy suggests using `try_fold` but it would actually lead to a different behavior

Open
#16,163 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

So I was working on this code where I apply an operation to a DB row to create an overlay for transactions.

This is done by the following function:

    /// Patches a row with the overlay changes.
    ///
    /// The return may be [`None`] if the row has been deleted in the overlay.
    ///
    /// NOTE: `clippy::manual_try_fold`
    /// this lint is TOTALLY WRONG HERE. We may have a row which first becomes None (deleted), then an insert again returns Some.
    #[allow(clippy::manual_try_fold)]
    pub fn patch_row(&self, row: Vec<(ColumnDef, Value)>) -> Option<Vec<(ColumnDef, Value)>> {
        // get primary key value
        let pk = row
            .iter()
            .find(|(col_def, _)| col_def.primary_key)
            .map(|(_, value)| value)
            .cloned()?;

        // apply all operations for this primary key to the row
        self.operations
            .iter()
            .filter(|op| op.primary_key_value() == &pk)
            .fold(Some(row), |acc, op| self.apply_operation(acc, op))
    }

Here, Clippy suggested using try_fold instead of fold, but this would lead to an unwanted behaviour.

apply_operation indeed can return Some even if row is None

/// Applies a single [`Operation`] to a row.
    fn apply_operation(
        &self,
        row: Option<Vec<(ColumnDef, Value)>>,
        op: &Operation,
    ) -> Option<Vec<(ColumnDef, Value)>> {
        match (row, op) {
            (_, Operation::Insert(_, record)) => Some(record.clone()), // it's definitely weird if we have `Some` row here, but just return the inserted record
            (_, Operation::Delete(_)) => None, // row is deleted; it would be weird to have `None` row here; just return None
            (None, Operation::Update(_, _)) => None, // trying to update a non-existing row; just return None
            (Some(mut existing_row), Operation::Update(_, updates)) => {
                for (col_name, new_value) in updates {
                    if let Some((_, value)) = existing_row
                        .iter_mut()
                        .find(|(col_def, _)| col_def.name == col_name)
                    {
                        *value = new_value.clone();
                    }
                }
                Some(existing_row)
            }
        }
    }

But by suggesting try_fold instead of fold, the iterator would short-circuit at the first None returned by apply_operation.

Clippy should not provide this lint in this case, since it would cause the code not to work as expected.

Lint Name

manual_try_fold

Reproducer

I tried this code:

enum Operation {
    Insert(i64, Vec<(&'static str, i64)>), // (row_id, record)
    Delete(i64),                           // row_id
    Update(i64, Vec<(&'static str, i64)>), // (row_id, [(column_name, new_value)])
}

impl Operation {
    fn primary_key_value(&self) -> &i64 {
        match self {
            Operation::Insert(pk, _) => pk,
            Operation::Delete(pk) => pk,
            Operation::Update(pk, _) => pk,
        }
    }
}

fn patch_row(
    operations: &[Operation],
    primary_key: &'static str,
    row: Vec<(&'static str, i64)>,
) -> Option<Vec<(&'static str, i64)>> {
    // get primary key value
    let pk = row
        .iter()
        .find(|(col, _)| *col == primary_key)
        .map(|(_, value)| value)
        .cloned()?;

    // apply all operations for this primary key to the row
    operations
        .iter()
        .filter(|op| op.primary_key_value() == &pk)
        .fold(Some(row), |acc, op| apply_operation(acc, op))
}

/// Applies a single [`Operation`] to a row.
fn apply_operation(
    row: Option<Vec<(&'static str, i64)>>,
    op: &Operation,
) -> Option<Vec<(&'static str, i64)>> {
    match (row, op) {
        (_, Operation::Insert(_, record)) => Some(record.clone()), // it's definitely weird if we have `Some` row here, but just return the inserted record
        (_, Operation::Delete(_)) => None, // row is deleted; it would be weird to have `None` row here; just return None
        (None, Operation::Update(_, _)) => None, // trying to update a non-existing row; just return None
        (Some(mut existing_row), Operation::Update(_, updates)) => {
            for (col_name, new_value) in updates {
                if let Some((_, value)) = existing_row.iter_mut().find(|(col, _)| col == col_name) {
                    *value = *new_value;
                }
            }
            Some(existing_row)
        }
    }
}

fn main() {
    let ops = vec![
        Operation::Insert(24, vec![("a", 1), ("b", 2)]),
        Operation::Update(24, vec![("a", 3)]),
        Operation::Update(24, vec![("b", 5)]),
        Operation::Delete(24),
        Operation::Insert(24, vec![("a", 7), ("b", 8)]),
    ];
    let result = patch_row(&ops, "id", vec![("id", 24), ("a", 0), ("b", 0)]);
    println!("Final result: {:?}", result);
}

I saw this happen:

warning: usage of `Iterator::fold` on a type that implements `Try`
  --> src/main.rs:33:10
   |
33 |         .fold(Some(row), |acc, op| apply_operation(acc, op))
   |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `try_fold` instead: `try_fold(row, |acc, op| ...)`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.91.0/index.html#manual_try_fold
   = note: `#[warn(clippy::manual_try_fold)]` on by default

I expected to see this happen:

No warning.
Also in this case it should tell to use directly apply_operation instead. In case you write apply_operation instead of |acc, op| apply_operation(acc, op) the warning is not reported.

Version
rustc 1.91.1 (ed61e7d7e 2025-11-07)
binary: rustc
commit-hash: ed61e7d7e242494fb7057f2657300d9e77bb4fcb
commit-date: 2025-11-07
host: aarch64-apple-darwin
release: 1.91.1
LLVM version: 21.1.2
Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the manual_try_fold lint and run the standalone Rust reproducer to confirm how the warning changes behavior when None is followed by an insert. Trace the lint's handling of the closure form and verify that the completed behavior avoids the incorrect suggestion for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.