A case where clippy suggests to use Some instead of unwrap
⚓ Rust 📅 2026-01-17 👤 surdeus 👁️ 1The following main.rs demonstrates a construct that I use and that clippy complains about:
fn divide(x : usize, y : usize) -> Option<usize> {
if y == 0 { None } else { Some( x / y ) }
}
fn main() {
let option = divide(4, 2);
let value = if option.is_some() { option.unwrap() } else { usize::MAX };
println!("4 / 2 = {}", value);
}
The actual clippy error message for this case is
warning: called `unwrap` on `option` after checking its variant with `is_some`
--> src/main.rs:6:40
|
6 | let value = if option.is_some() { option.unwrap() } else { usize::MAX };
| ------------------- ^^^^^^^^^^^^^^^
| |
| help: try: `if let Some(<item>) = option`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.92.0/index.html#unnecessary_unwrap
= note: `#[warn(clippy::unnecessary_unwrap)]` on by default
It is not clear to me what clippy is suggesting ?
7 posts - 3 participants
🏷️ Rust_feed