Avoid unwrap

unwrap Clippy

You might have seen a lot of code using unwrap and even more people telling you not to use unwrap in production code.

unwrap is one of the easy ways to disregard errors in Rust. It might be nice in examples so the reader can focus on the rest of the code, it might be good in tests where we want to have a panic if something goes wrong.

However, in general it is not that good to have in the code.

Luckily Clippy can help us.

Some simple code that uses unwrap

examples/avoid-unwrap/src/main.rs

fn main() {
    let input = "42";
    let answer = input.parse::<u32>().unwrap();
    println!("The answer is {answer}");
}

This code works.

Configure clippy to avoid unwrap

examples/avoid-unwrap/Cargo.toml

[package]
name = "avoid-unwrap"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[lints.clippy]
unwrap_used = "deny"


By adding 2 lines to the Cargo.toml file we can tell Clippy to report an error when unwrap is encountered in the code.

[lints.clippy]
unwrap_used = "deny"

When I ran cargo clippy this is the error message I received:

$ cargo clippy
    Checking avoid-unwrap v0.1.0 (/home/gabor/work/rust.code-maven.com/examples/avoid-unwrap)
error: used `unwrap()` on a `Result` value
 --> src/main.rs:3:18
  |
3 |     let answer = input.parse::<u32>().unwrap();
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: if this value is an `Err`, it will panic
  = help: consider using `expect()` to provide a better panic message
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
  = note: requested on the command line with `-D clippy::unwrap-used`

error: could not compile `avoid-unwrap` (bin "avoid-unwrap") due to previous error

Referring to unwrap used.

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo