Skip to content

sort fields in struct instantiation #16148

@amab8901

Description

@amab8901

What it does

Warns if keys aren't alphabetically sorted when instantiating a struct

Advantage

Easier/quicker to find the key you're looking for if it's alphabetically sorted, especially for large structs with many fields.

Drawbacks

idk

Example

fn main() {
    let structy = Structy {
        field12: "a".to_owned(),
        field4: "a".to_owned(),
        field13: "a".to_owned(),
        field6: "a".to_owned(),
        field11: "a".to_owned(),
        field7: "a".to_owned(),
        field1: "a".to_owned(),
        field8: "a".to_owned(),
        field15: "a".to_owned(),
        field2: "a".to_owned(),
        field9: "a".to_owned(),
        field10: "a".to_owned(),
        field5: "a".to_owned(),
        field14: "a".to_owned(),
        field3: "a".to_owned(),
    };

    dbg!(structy);
}

#[derive(Debug)]
pub struct Structy {
    pub field1: String,
    pub field2: String,
    pub field3: String,
    pub field4: String,
    pub field5: String,
    pub field6: String,
    pub field7: String,
    pub field8: String,
    pub field9: String,
    pub field10: String,
    pub field11: String,
    pub field12: String,
    pub field13: String,
    pub field14: String,
    pub field15: String,
}

Could be written as:

fn main() {
    let structy = Structy {
        field1: "a".to_owned(),
        field2: "a".to_owned(),
        field3: "a".to_owned(),
        field4: "a".to_owned(),
        field5: "a".to_owned(),
        field6: "a".to_owned(),
        field7: "a".to_owned(),
        field8: "a".to_owned(),
        field9: "a".to_owned(),
        field10: "a".to_owned(),
        field11: "a".to_owned(),
        field12: "a".to_owned(),
        field13: "a".to_owned(),
        field14: "a".to_owned(),
        field15: "a".to_owned(),
    };

    dbg!(structy);
}

#[derive(Debug)]
pub struct Structy {
    pub field1: String,
    pub field2: String,
    pub field3: String,
    pub field4: String,
    pub field5: String,
    pub field6: String,
    pub field7: String,
    pub field8: String,
    pub field9: String,
    pub field10: String,
    pub field11: String,
    pub field12: String,
    pub field13: String,
    pub field14: String,
    pub field15: String,
}

Comparison with existing lints

I think there's a lint that lets u sort the fields in the struct definition, but I couldn't find a lint for sorting the fields in the instantiation of the same struct

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions