39 lines
1.2 KiB
Plaintext
39 lines
1.2 KiB
Plaintext
![]() |
== Why is this an issue?
|
||
|
|
||
|
Using `unwrap()` in conditions where it will always fail leads to unexpected panics and unclear error handling. It's likely a mistake and checking that there is indeed a wrapped value and not a none one was intended instead, which would require inverting the condition. However, if panicking was indeed intended, then one should use `panic!` explicitly to make the intention clear and readable.
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
||
|
----
|
||
|
let option = Some(0);
|
||
|
fn do_something_with(_x: usize) {}
|
||
|
if option.is_none() {
|
||
|
do_something_with(option.unwrap()); // Noncompliant: This code will always panic.
|
||
|
}
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,rust,diff-id=1,diff-type=compliant]
|
||
|
----
|
||
|
let option = Some(0);
|
||
|
fn do_something_with(_x: usize) {}
|
||
|
if option.is_some() {
|
||
|
do_something_with(option.unwrap()); // Compliant: Inverted condition to ensure unwrap is safe.
|
||
|
}
|
||
|
|
||
|
// or
|
||
|
|
||
|
if option.is_none() {
|
||
|
panic!("Option was none when it was expected to be some."); // Compliant: Explicit panic with a message.
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Resources
|
||
|
=== Documentation
|
||
|
|
||
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#panicking_unwrap
|