rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`filter_map_bool_then` borrow check error

Open ronnodas opened this issue 3 months ago • 1 comments

Summary

If the predicate and the operation inside the then() both need access to the same object, at least one needing exclusive access, then the filter_map(... then(...)) cannot be split up as .filter(...).map(...). However the lint still triggers.

Lint Name

filter_map_bool_then

Reproducer

I tried this (minimized) code (playground link):

#![deny(clippy::filter_map_bool_then)]

pub fn main() {
    let mut last = None;
    let dedup: Vec<u32> = [1, 2, 2, 3]
        .into_iter()
        .filter_map(|val| {
            (last != Some(val)).then(|| {
                last = Some(val);
                val
            })
        })
        .collect();
    println!("{:?}", dedup);
}

I saw this happen:

error: usage of `bool::then` in `filter_map`
  --> src/main.rs:7:10
   |
 7 |           .filter_map(|val| {
   |  __________^
 8 | |             (last != Some(val)).then(|| {
 9 | |                 last = Some(val);
10 | |                 val
11 | |             })
12 | |         })
   | |__________^
   |
   = help: consider using `filter` then `map` instead
   = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#filter_map_bool_then
note: the lint level is defined here
  --> src/main.rs:1:9
   |
 1 | #![deny(clippy::filter_map_bool_then)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I expected to see this happen: Nothing, since this operation can't be split into a filter() followed by a map().

Version


Additional Labels

@rustbot label +I-suggestion-causes-error

ronnodas avatar Aug 25 '26 07:08 ronnodas

@rustbot claim

kennywillbe avatar Aug 31 '26 23:08 kennywillbe