Skip to content

new lint: warn if we match on index item and use wildcard pattern #5500

@matthiaskrgr

Description

@matthiaskrgr

Inspired by #5499

pub fn main() {
    let x = vec![1,2,3];
    match_vec_idx(4 /*boom*/, x);
}

fn match_vec_idx(idx: usize, vec: Vec<u32>) -> bool {
    match vec[idx] {
        1 => return true,
        2 => return false,
        _ => {}
    }
return false
}

In this code we can see that we match on an item in a certain vector position, we only care about a limited number of cases and ignore the rest.

This code will panic if the idx is out of bounds, as it is the case here.
If we could lint the

match x[y] => {
   something => something_else,
   _  => {}
}

pattern where nothing happens anyway if we don't find any of the matched patterns in the vector position, we could suggest using .get() and avoid the panic:

pub fn main() {
    let x = vec![1,2,3];
    match_vec_idx(4/*no longer boom*/, x);
}

fn match_vec_idx(idx: usize, vec: Vec<u32>) -> bool {
    match vec.get(idx) { // use .get()
        Some(1) => return true, // wrapped in Some()
        Some(2) => return false, // wrapped in Some()
        _ => {}
    }
return false
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-styleLint: Belongs in the style lint groupT-ASTType: Requires working with the ASTgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions