rust-lang / rust-lang/rust-clippy
`option_if_let_else` suggests invalid code when using mut references in the else clause
Open
@dswij is already working on this.
Since Jan 23, 2022.
C-bug
I-false-positive
L-nursery
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
There is a conditional branching code that uses if let else for the return value of HashMap::get_mut().
Even though the else clause of this code uses a mutable reference of the HashMap, option_if_let_else suggests to use map_or_else(), but the suggested code causes an error in the borrow checker.
Lint Name
option_if_let_else
Reproducer
I tried this code:
// feature_ids is a HashMap.
if let Some(v) = feature_ids.get_mut(&fid) {
*v += 1.0;
} else {
feature_ids.insert(fid, 1.0);
}
I saw this happen:
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else
help: try
|
150 ~ feature_ids.get_mut(&fid).map_or_else(|| {
151 + feature_ids.insert(fid, 1.0);
152 + }, |v| {
153 + *v += 1.0;
154 + })
The suggested code is not compilable:
|
150 | feature_ids.get_mut(&fid).map_or_else(|| {
| ------------------------- ----------- ^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
151 | feature_ids.insert(fid, 1.0);
| ----------- second borrow occurs due to use of `feature_ids` in closure
Version
rustc 1.59.0-nightly (7abab1efb 2021-12-17)
binary: rustc
commit-hash: 7abab1efb21617ba6845fa86328dffa16cfcf1dc
commit-date: 2021-12-17
host: x86_64-apple-darwin
release: 1.59.0-nightly
LLVM version: 13.0.0
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.