Skip to content

false negative if_same_then_else / new lint catch wrongly ordered struct init shorthand #6352

Closed
@matthiaskrgr

Description

@matthiaskrgr

Upstream rustc issue: rust-lang/rust#79210

This is definitely also clippy territory!
We have the if_same_than_else lint which probably should catch the upstream example, but I wonder if we could have a lint that catches the field ordering being suspicious.

I tried this code:

#[derive(Debug)]
struct S {
    a: i32,
    b: i32,
}

fn main() {
    let a = 0_i32;
    let b = 1_i32;
    let s: S = if false {
        S { a, b }
    } else {
        S { b, a } /* wanted: S {a: b, b: a}*/
    };
    println!("{:?}", s);
}

The problem is that S { a, b } and S { b, a } is essentially the same, but the if_same_then_else lint did not see this (probably because of the field ordering).
Alternatively, I wonder if it makes sense to have a lint that generally warns we use the shorthand init pattern

struct S { a: i32, b: i32, c: i32 }
let a = 1;
let b = 2;
let c = 3;
let s = S { c, a, b }

where the struct members are not listed in the order that they are defined in the struct definition.

clippy 0.0.212 (fe98231 2020-11-19)

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsC-bugCategory: Clippy is not doing the correct thingE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.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