rust-lang / rust-lang/rust-clippy
`map_unwrap_or` suggests code that does not compile
Open
@profetia is already working on this.
Since Apr 16, 2026.
C-bug
I-false-positive
I-suggestion-causes-error
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
Clippy suggestion does not compile.
The pattern is this:
some_option_that_borrows_mutably
.map(func)
.unwrap_or_else(closure_that_borrows_immutably)
After applying the suggestion there is a borrow error.
Lint Name
clippy::map_unwrap_or
Reproducer
I tried this code:
#[warn(clippy::map_unwrap_or)]
fn main() {
let mut v = [1, 2, 3];
let w: Vec<_> = v.iter_mut().collect();
let _ = w.into_iter().next().map(|x| *x).unwrap_or_else(|| *v.iter().max().unwrap());
}
I saw this happen:
warning: called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling `map_or_else(<g>, <f>)` instead
--> src/main.rs:6:13
|
6 | let _ = w.into_iter().next().map(|x| *x).unwrap_or_else(|| *v.iter().max().unwrap());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `w.into_iter().next().map_or_else(|| *v.iter().max().unwrap(), |x| *x)`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_unwrap_or
note: the lint level is defined here
--> src/main.rs:1:8
|
1 | #[warn(clippy::map_unwrap_or)]
| ^^^^^^^^^^^^^^^^^^^^^
After applying the lint:
#[warn(clippy::map_unwrap_or)]
fn main() {
let mut v = [1, 2, 3];
let w: Vec<_> = v.iter_mut().collect();
let _ = w.into_iter().next().map_or_else(|| *v.iter().max().unwrap(), |x| *x);
}
This is the error:
error[[E0502]](https://doc.rust-lang.org/stable/error_codes/E0502.html): cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:6:46
|
5 | let w: Vec<_> = v.iter_mut().collect();
| ------------ mutable borrow occurs here
6 | let _ = w.into_iter().next().map_or_else(|| *v.iter().max().unwrap(), |x| *x);
| ----------- ^^ - second borrow occurs due to use of `v` in closure
| | |
| | immutable borrow occurs here
| mutable borrow later used by call
For more information about this error, try `rustc --explain E0502`.
Link to playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=51f5cf8dafd635de05f2a59d1383287e
Version
rustc 1.73.0-nightly (7bd81ee19 2023-07-13)
binary: rustc
commit-hash: 7bd81ee1902c049691d0a1f03be5558bee51d100
commit-date: 2023-07-13
host: x86_64-pc-windows-msvc
release: 1.73.0-nightly
LLVM version: 16.0.5
Additional Labels
@rustbot label +I-suggestion-causes-error
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.