Skip to content

New lint: slice_indexing_after_deconstruction #7569

Closed
@xFrednet

Description

@xFrednet

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 with if let statements. I think it would be reasonable for this lint to also check if statements inside if_chain macros.
  • The lint probably shouldn't warn if the slice instance is used for something else besides direct value access.

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions