RS.CLIPPY.INDEX_REFUTABLE_SLICE
Avoid indexing on slices which could be destructed
What it does
The lint checks for slice bindings in patterns that are only used to access individual slice values.
Why is this bad?
Accessing slice values using indices can lead to panics. Using refutable patterns can avoid these. Binding to individual values also improves the readability as they can be named.
Limitations
This lint currently only checks for immutable access inside if let
patterns.
Example
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
if let Some(slice) = slice {
println!("{}", slice[0]);
}
Use instead:
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
if let Some(&[first, ..]) = slice {
println!("{}", first);
}
Configuration
-
max-suggested-slice-pattern-length: When Clippy suggests using a slice pattern, this is the maximum number of elements allowed in the slice pattern that is suggested. If more elements are necessary, the lint is suppressed. For example,[_, _, _, e, ..]is a slice pattern with 4 elements.(default:
3) -
msrv: The minimum rust version that the project supports. Defaults to therust-versionfield inCargo.toml(default:
current version)