Closed
Description
Summary
I encountered this error during Advent of Code where Clippy suggests to change an Option::then
to then_some
. I used std::ops::Range::contains()
to make sure the closure passed to then
is safe to call. It can panic when the number is not within the range and should not be evaluated eagerly.
I'm not sure if a lint like this could possibly take outside context into account but it's a false positive nonetheless.
Lint Name
unnecessary_lazy_evaluations
Reproducer
The version with then
use std::ops::Range;
fn main() {
let map = Mapping {
range: 10..20,
offset: 10,
};
println!("{:?}", map.get(10));
println!("{:?}", map.get(9));
}
struct Mapping {
range: Range<u64>,
offset: u64,
}
impl Mapping {
fn get(&self, seed: u64) -> Option<u64> {
// This can panic when replaced with then_some().
self.range.contains(&seed).then(|| {
seed - self.offset
})
}
}
works as expected.
The version with then_some
use std::ops::Range;
fn main() {
let map = Mapping {
range: 10..20,
offset: 10,
};
println!("{:?}", map.get(10));
println!("{:?}", map.get(9)); // panics here
}
struct Mapping {
range: Range<u64>,
offset: u64,
}
impl Mapping {
fn get(&self, seed: u64) -> Option<u64> {
self.range.contains(&seed).then_some({
seed - self.offset
})
}
}
Version
rustc 1.74.0 (79e9716c9 2023-11-13)
binary: rustc
commit-hash: 79e9716c980570bfd1f666e3b16ac583f0168962
commit-date: 2023-11-13
host: x86_64-unknown-linux-gnu
release: 1.74.0
LLVM version: 17.0.4
Additional Labels
No response