Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

sorted-fields

Level: warn · Fixed by rabot fmt · Article: Sorting

Sort alphabetically. Every time. Object properties, table columns, class methods, enum values. Everything that forms a list.

What it checks

Named fields of a struct, and of struct-like enum variants, are in alphabetical order (case-insensitive, field2 before field10). A blank line starts a new group, sorted on its own; see groups. Tuple fields are positional and never sorted.

Types whose field order is behaviour are skipped without a diagnostic: #[repr(..)] types (the layout is the point), types deriving PartialOrd or Ord (comparison goes field by field), and types with a derive from order-sensitive-derives: clap’s positional arguments, uniffi’s generated constructors, positional binary encodings. See what is left alone.

Don’t

#![allow(unused)]
fn main() {
struct User {
    id: UserId, // primary key first, obviously
    email: Email,
    name: UserName,
    created_at: DateTime, // metadata at the end
    updated_at: DateTime,
    last_login_at: Option<DateTime>,
    phone_number: Option<PhoneNumber>, // where does this go?
}
}

The logic lives in one developer’s head. The next developer tacks phone_number at the bottom because that is the safe move. Six developers later, the struct is sediment.

Do

#![allow(unused)]
fn main() {
struct User {
    created_at: DateTime, // metadata at the end
    email: Email,
    id: UserId, // primary key first, obviously
    last_login_at: Option<DateTime>,
    name: UserName,
    phone_number: Option<PhoneNumber>, // where does this go?
    updated_at: DateTime,
}
}

Nobody asks where phone_number goes. P comes after N, before U.

If fields belong together, say so with a blank line. rabot sorts each group on its own and never moves a field across the line:

#![allow(unused)]
fn main() {
struct User {
    first_name: UserName,
    last_name: UserName,

    email: Email,
    phone_number: Option<PhoneNumber>,

    created_at: DateTime,
    last_login_at: Option<DateTime>,
    updated_at: DateTime,
}
}

When a group keeps travelling together, through signatures and from one struct to the next, it is a type waiting to be named:

#![allow(unused)]
fn main() {
struct User {
    contact: UserContact,
    name: UserName,
}
}

Silence it

#![allow(unused)]
fn main() {
// Deliberately unsorted: drop order matters, the guard must release before the pool.
struct Connection {
    guard: MutexGuard<'static, ()>,
    pool: Pool,
}
}

Field order also decides Debug output and serde’s field order. Those are rarely a reason; when they are, write them down. When a derive of yours reads field order (a binary encoding, code generation), add it to order-sensitive-derives instead, and every type deriving it is left alone.