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-variants

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

One rule. Zero documentation required. Culturally neutral.

What it checks

Enum variants are in alphabetical order. Enums whose variant order is behaviour are skipped without a diagnostic: #[repr(..)] enums, enums with explicit discriminants (A = 1), enums deriving PartialOrd or Ord (declaration order is the comparison order), #[serde(untagged)] enums (serde tries the variants top to bottom), and enums with a derive from order-sensitive-derives, such as strum’s EnumIter. See what is left alone.

A blank line starts a new group of variants, sorted on its own; see groups.

Don’t

#![allow(unused)]
fn main() {
enum UserRole {
    Member,
    Admin,
    Guest { invited_by: UserId, since: DateTime },
}
}

Do

#![allow(unused)]
fn main() {
enum UserRole {
    Admin,
    Guest { invited_by: UserId, since: DateTime },
    Member,
}
}

Fields of a struct-like variant are sorted too (that is sorted-fields).

Silence it

An enum whose order carries meaning usually says so already: derive PartialOrd and rabot steps aside. When the meaning is a derive of your own, add it to order-sensitive-derives. When it is not a derive, write it down:

#![allow(unused)]
fn main() {
// Deliberately unsorted: matches the on-wire protocol numbering.
enum Opcode { Connect, Publish, Subscribe, Disconnect }
}