Closed
Description
What it does
The lint checks for slices that come from value deconstruction and are only used to access individual slice values.
Categories (optional)
- Kind: pedantic (This could also be style, but I'm not sure if we want it warn-by-default.)
Advantages
Deconstruction of slices allows direct value access without using indexes on the slice, which can lead to panics. It also enables the user to give slice values a better name and indirectly check the correct length of the slice. See #7566 files as an example of how this can be an improvement.
Clippy already had a few instances where ICEs would have been prevented by using deconstruction of slices.
Example
fn main() {
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
if let Some(slice) = slice {
println!("{}", slice[0]);
}
}
Could be written as:
fn main() {
let slice: Option<&[u32]> = Some(&[1, 2, 3]);
if let Some([first, ..]) = slice {
println!("{}", first);
}
}
Notes:
- Clippy uses pattern matching extensively, often in
if_chain
macros withif let
statements. I think it would be reasonable for this lint to also check if statements insideif_chain
macros. - The lint probably shouldn't warn if the slice instance is used for something else besides direct value access.