RS.CLIPPY.GET_UNWRAP
Using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead
This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: get_unwrap. Copyright ©2025 The Rust Team. All rights reserved.
What it does
Checks for usage of .get().unwrap() (or
.get_mut().unwrap) on a standard library type which implements Index
Why restrict this?
Using the Index trait ([]) is more clear and more
concise.
Known problems
Not a replacement for error handling: Using either
.unwrap() or the Index trait ([]) carries the risk of causing a panic
if the value being accessed is None. If the use of .get().unwrap() is a
temporary placeholder for dealing with the Option type, then this does
not mitigate the need for error handling. If there is a chance that .get()
will be None in your program, then it is advisable that the None case
is handled in a future refactor instead of using .unwrap() or the Index
trait.
Example
let mut some_vec = vec![0, 1, 2, 3];
let last = some_vec.get(3).unwrap();
*some_vec.get_mut(0).unwrap() = 1;
The correct use would be:
let mut some_vec = vec![0, 1, 2, 3];
let last = some_vec[3];
some_vec[0] = 1;