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-struct-literal

Level: warn · Fixed by rabot fmt (when safe) · Article: Sorting

What it checks

The fields of a struct literal, User { .. }, are in alphabetical order, the same order as the definition. ..base stays last.

rabot only rewrites a literal when every initializer is plainly side-effect free: literals, paths, field accesses, references, Some(..), clone(), Default::default() and the like. Initializers are evaluated in source order, so a literal with calls in it is reported and left for you to reorder by hand.

Don’t

#![allow(unused)]
fn main() {
impl User {
    fn from_signup(input: Signup, now: DateTime) -> Self {
        User {
            role: Role::Member,
            name: input.name,
            id: UserId::new(),
            email: input.email,
            created_at: now,
        }
    }
}
}

Do

#![allow(unused)]
fn main() {
impl User {
    fn from_signup(input: Signup, now: DateTime) -> Self {
        User {
            created_at: now,
            email: input.email,
            id: UserId::new(),
            name: input.name,
            role: Role::Member,
        }
    }
}
}

Same order as the struct, every time it is built. A reviewer comparing the two never has to hunt.

Silence it

#![allow(unused)]
fn main() {
// rabot: allow(sorted-struct-literal) initializers must run in this order: the token is minted before the session
Session { token: mint(&mut rng), id: next_id(&mut rng) }
}