-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Closed
Labels
A-lintArea: New lintsArea: New lintsL-styleLint: Belongs in the style lint groupLint: Belongs in the style lint groupT-ASTType: Requires working with the ASTType: Requires working with the ASTgood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy
Description
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
Labels
A-lintArea: New lintsArea: New lintsL-styleLint: Belongs in the style lint groupLint: Belongs in the style lint groupT-ASTType: Requires working with the ASTType: Requires working with the ASTgood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy