go icon indicating copy to clipboard operation
go copied to clipboard

cmd/gofmt: trailing comments in composite literals are misaligned

Open mibk opened this issue 2 weeks ago • 4 comments

Go version

go version go1.25.5 darwin/arm64

Description

I noticed that gofmt produces the following formatting for a byte slice literal:

fr.Write([]byte{
	0x00,       // Preamble
	0x00, 0xFF, // Start code
	dlen,      // LEN
	^dlen + 1, // LCS
	tfi,       // Type of Frame Identifier
})

My expectation was that comments would remain aligned consistently. Is this a known limitation or intended behavior of gofmt? Apologies if this was already reported.

(Go 1.24 produces the same output: https://go.dev/play/p/jxcnuqd6IsA?v=goprev)

mibk avatar Dec 05 '25 08:12 mibk

CC @griesemer, @mvdan.

dmitshur avatar Dec 05 '25 14:12 dmitshur

My guess is that between the second and third comment, the line length decreases enough where it starts a new "comment alignment chunk", which just happens to be one character to the left, as the fourth comment is the longest of that second chunk.

This is more apparent if you increase the difference:

package main

func main() {
	fr.Write([]byte{
		0x00,                   // Preamble
		0x00, 0xFF, 0xFF, 0xFF, // Start code
		dlen,      // LEN
		^dlen + 1, // LCS
		tfi,       // Type of Frame Identifier
	})
}

I guess you could try tweaking the heuristic so that it doesn't split comment alignment chunks if the difference is very small. However, note that this could have surprising knock-on effects; what if we have ten consecutive chunks which each decrease the alignment level by one? Should they all gain whitespace with the change?

mvdan avatar Dec 05 '25 15:12 mvdan

It's easier to see the desired behavior when the difference in length is larger: https://go.dev/play/p/n0dnfZkATl3?v=goprev

I'm sure there are unfortunate edge cases (like yours) where the behavior is a little unexpected, but changes to the formatter are very disruptive for the whole Go community, so I don't see a compelling reason to change the algorithm here.

adonovan avatar Dec 05 '25 15:12 adonovan