unwrap() inside a branch already guarded by is_some()/is_ok()
ID |
rust.maintainability.unnecessary_unwrap |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Idiom |
Language |
Rust |
Description
Reports a call to unwrap() on a value inside the if branch that has just tested the same value with is_some() or is_ok().
Rationale
The test and the unwrap inspect the value twice and keep the guarantee only in the programmer’s head: nothing ties them together, so moving the unwrap out of the branch, or adding a condition to the if, turns working code into a panic with no compiler complaint. The pattern also leaves the inner value borrowed rather than bound, which forces extra clones or as_ref() calls further down.
The following code illustrates the pattern detected by this rule:
fn label(name: Option<String>) -> String {
if name.is_some() {
// FLAGGED: unwrap() inside a branch already guarded by is_some()/is_ok()
name.unwrap()
} else {
"anonymous".to_string()
}
}