Proposal Details
Sometimes you have relatively simple switch statements that look like:
switch color {
case MintCream:
return "#F5FFFA"
case Azure:
return "#F0FFFF"
case AliceBlue:
return "#F0F8FF"
case GhostWhite:
return "#F8F8FF"
...
}
In terms of total lines, this can get quite long.
I propose that we modify gofmt to permit keeping the case expression and the following statement on the same line if the statement is also a single line.
Thus, the above can be written as:
switch color {
case MintCream: return "#F5FFFA"
case Azure: return "#F0FFFF"
case AliceBlue: return "#F0F8FF"
case GhostWhite: return "#F8F8FF"
...
}
and gofmt won't try to rewrite into the expanded form. It will however, column align all vertically adjacent statements.
To be clear, I'm not proposing that gofmt rewrite existing expanded switch statements into the compact form,
only that it avoid expanding it if the author deliberately wrote it in the compact form.
The benefit of this is increased readability and consistency:
- Readability: All the color enums vertically appear together as a column without any interspersed color values. Similarly, all the color values appear together in a single column. Also, this representation takes half the lines, and so makes more efficient use of more of the editor pane's width.
- Consistency: There is syntactic similarity with something like a Go map literal:
color := map[Color]string{
MintCream: "#F5FFFA",
Azure: "#F0FFFF",
AliceBlue: "#F0F8FF",
GhostWhite: "#F8F8FF",
...
}
As with any formatting change, this can lead to less readable code, but the at least this change allows the programmer to best decide what is most readable and not have gofmt expand the whole switch statement. It also avoids the temptation to use a map literal just because it is more compact.
Proposal Details
Sometimes you have relatively simple switch statements that look like:
In terms of total lines, this can get quite long.
I propose that we modify
gofmtto permit keeping thecaseexpression and the following statement on the same line if the statement is also a single line.Thus, the above can be written as:
and
gofmtwon't try to rewrite into the expanded form. It will however, column align all vertically adjacent statements.To be clear, I'm not proposing that
gofmtrewrite existing expanded switch statements into the compact form,only that it avoid expanding it if the author deliberately wrote it in the compact form.
The benefit of this is increased readability and consistency:
As with any formatting change, this can lead to less readable code, but the at least this change allows the programmer to best decide what is most readable and not have
gofmtexpand the whole switch statement. It also avoids the temptation to use a map literal just because it is more compact.