Why does rustfmt remove trailing comma in `#![feature(...)]`?

In contrast, in #[derive(...)] for example, it adds it.

Edit: I mean when the statement is multiline.

1 Like

rustfmt usually doesn't add a trailing comma for #[derive(...)]. You can go to this playground and run the rustfmt tool to see this.
You probably have some local configuration that's making rustfmt add trailing commas.

When they exceed one line it does: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=154655de17a9b6c20b7b46d5d4c09de8

I think rustfmt adds the trailing comma whenever it formats a long list to by multiline, with 1 item per line. If you have a lot of derives, it'll format them like that, with each item on its own line:

#[derive(
    Debug,
    FFFFFFFFFFF,
    FFFFFFF,
    FFFFFFFFFF,
    FFFFFFFFF,
    FFFFFFFFFF,
    FFFFFFFFFF,
    FFFFFFFFF,
    FFFFF,
    FFFF,
    FFFFFFFF,
    FFFFFFFFFFFF,
    FFFFFFFFFF,
    FFFFFFF,
)]
struct Foo(i32);

But for the feature flags, it seems to prefer wrapping the line:

#![feature(
    Foo, Bar, Baz, Quux, Blah, Blahhh, Blahhhh, F, FF, FFF, FFFF, FFFFF, FFFFFFFFFF, A, AA, AAA, B,
    BB, BBB, BBBB
)]

So I guess the real question is, why does rustfmt wrap text for a long list of feature flags, but split into lines for everything else?
It might be because you don't usually have a ton of feature flags all enabled at once. I might be wrong though, since I don't really use nightly.

Not true. For all it prefers wrapping until some length, then multiline. Probably your #[derive(...)] is longer.

After cargo fmt:

fn main() {}

#[derive(
    Longaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, B,
)]
#[feature(
    Longaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
    B
)]
struct S {}

It seems like derive has some special handling, if you change it to "deriv" for example it's formatted to multiline instead (even though it's actually shorter now). I'm not sure why that is, but I would guess that it's because long derives are more common and often have many traits that are not always that interesting (Debug, Default, PartialEq, Eq...), so making them multiline would make the code less readable.

1 Like