RS.CLIPPY.INDEX_REFUTABLE_SLICE

Avoid indexing on slices which could be destructed

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: index_refutable_slice. Copyright ©2025 The Rust Team. All rights reserved.

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 the rust-version field in Cargo.toml

    (default: current version)