Skip to content

Comment between a #[cfg] attribute and a non-shorthand struct-pattern field duplicates the field identifier #6984

Description

@kostekIV

Summary

When a line comment appears between an attribute (e.g. #[cfg(...)]) and a
non-shorthand field (name: pattern) in a struct pattern, rustfmt emits the
field identifier twice, producing code that no longer compiles.

I tried to format this code:

fn main() {
    let Demo {
        #[cfg(feature = "diagnostics")]
        // comment between attribute and field
        field_name_baz: _,
    } = value;
}

Expected behavior

I expected the field to be left unchanged (the comment kept between the
attribute and the field):

  fn main() {
      let Demo {
          #[cfg(feature = "diagnostics")]
          // comment between attribute and field
          field_name_baz: _,
      } = value;
  }

Actual behavior

Instead, the field identifier field_name_baz: is emitted twice, and the field
is over-indented:

  fn main() {
      let Demo {
          #[cfg(feature = "diagnostics")]
              // comment between attribute and field
              field_name_baz:
              field_name_baz: _,
      } = value;
  }

The duplicated field_name_baz: makes the output invalid Rust. This only affects
non-shorthand fields (name: pattern); shorthand fields (field_name_baz
with no : pattern) format correctly.

Configuration

rustfmt cli options used (if applicable):

$ rustfmt

(Reproduces with the default configuration; also reproduces with
style_edition = "2024".)

rustfmt configuration file (e.g. rustfmt.toml, if applicable):

(none)

Reproduction Steps

  1. Save the snippet above to repro.rs.
  2. Run rustfmt repro.rs (or cargo fmt).
  3. Observe that field_name_baz: appears twice in the output.

or quick bash cmd:

echo 'fn main() {
      let Demo {
          #[cfg(feature = "diagnostics")]
          // comment between attribute and field
          field_name_baz: _,
      } = value;
  }' | env DYLD_LIBRARY_PATH=$(rustc --print sysroot)/lib ./target/debug/rustfmt

Meta

rustfmt --version:
rustfmt 1.10.0-nightly (76d2c6d 2026-07-23)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-commentsArea: commentsC-bugCategory: this is a bug; use also I-* labels for specific bug kinds, e.g. I-non-idempotency or I-ICEI-invalid-codeIssue: formatting causes compile-pass code to compile-fail

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions