Skip to content

new lint: vector access via index after is_empty() #3029

Open

Description

#[cfg_attr(feature = "cargo-clippy", allow(pedantic))]

fn main() {
    let v: Vec<i32> = Vec::new();
    println!("{}", do_something(&v));
}

fn do_something(v: &[i32]) -> i32 {
    if v.is_empty() {
        // v must not be modified in between or be immutable
        v[0] //    BOOM    <- catch this at linttime
    } else {
        124
    }
}

// similar:
// if !v.is_empty() {
//      //...
// } else {
//   v[0]
// }

There are probably other std::collections where this can also be applied.

The idea of this ticket was inspired by cppcheck :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-correctnessLint: Belongs in the correctness lint groupT-MIRType: This lint will require working with the MIR

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions