Skip to content

single_match: recongnize "Ok(_) => {}" or "Err(_bla) => {}" as "_ => {}"  #2567

Open
@matthiaskrgr

Description

@matthiaskrgr

If we match a Result<x,y> , and we see that one of the results is ignored via
Ok(_) => {} or Err(_bla) => {}, can we somehow simplify this to _ => {} ?
The idea is that since we know that Result will either return Ok or Error, no other values are possible, which is why I think

match x {
Ok(_) => {},
Err(a) => { do_something(a) },
}

is equivalent to

match x {
Err(a) => { do_something(a) },
_ => {},
}

however, the second example will trigger single_match lint while the first one will not.

code sample:

fn main() {
    test1();
    test2();
    test3();
    test4();
}

fn test1() {
    // false negative
    match is_ok(3) {
        Ok(_a) => {}
        Err(bad) => {
            println!("very bad: {}", bad);
        }
    }
}

fn test2() {
    // false negative
    match is_ok(3) {
        Ok(_) => {}
        Err(bad) => {
            println!("very bad: {}", bad);
        }
    }
}

fn test3() {
    // true positive
    match is_ok(3) {
        Err(bad) => {
            println!("very bad: {}", bad);
        }
        _ => {}
    }
}

fn test4() {
    // true positive
    match is_ok(3) {
        Ok(good) => {
            println!("very good: {}", good);
        }
        _ => {}
    }
}

fn is_ok(x: i32) -> Result<bool, String> {
    if x > 1 {
        Ok(true)
    } else {
        Err("Oh no".to_string())
    }
}

Does this make sense?

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-false-negativeIssue: The lint should have been triggered on code, but wasn't

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions