Reason for non-indented case statements in switch (go fmt)

2,091 views
Skip to first unread message

Michael Whatcott

unread,
Aug 24, 2015, 3:27:53 PM8/24/15
to golang-nuts
I'm not asking for a change here. I already accept that go fmt is the way it is and I'm ok with it. I'm hoping for a reason for an inconsistency which has already been debated:  Un-indented case labels in the switch statement. First, some examples. 

Types:

type Something struct {
   
Field1 int // indented
   
Field2 int // indented
}



Functions:

func main() {
    log
.Fatal("GOPHERS!") // indented
}



If:

if something {
    log
.Fatal("GOPHERS!") // indented
}



Loops:

for {
    panic
("GOPHERS!") // indented
}



Why aren't the `case` and `default` statements within switch statements similarly indented?

switch blah {
case 1:      // not indented!!!
    panic
(1) // indented
case 2:      // not indented!!!
    panic
(2) // indented
default:     // not indented!!!
    panic
(3) // indented
}



It seems like it should look like this:

switch blah {
   
case 1:      // indented
        panic
(1) // indented
   
case 2:      // indented
        panic
(2) // indented
   
default:     // indented
        panic
(3) // indented
}



The general trend is: indent code within curly braces one level. But this isn't the case with the switch statement. Is there a historical trend for this inconsistency? Or was it a mistake when coding go fmt initially and it just stuck? Or just someone's preference? I can live with any of those answers, just curious. Again, I'm not pushing for a change, just voicing the question that pops into my head every time I write a switch statement in go.

Thanks.




Roberto Zanotto

unread,
Aug 24, 2015, 3:40:26 PM8/24/15
to golang-nuts
I think the reason is that the current formatting already makes clear what's the switch scope and what are the scopes of the cases. Too much indentation makes code ugly (IMO).

C Banning

unread,
Aug 24, 2015, 3:45:22 PM8/24/15
to golang-nuts
if blah == 1 {
   panic(1)
} else if blah == 2 {
   panic(2)
} else if blah == 3 {
   panic(3)
}

vs.

switch blah {
case 1:
   panic(1)
case 2:
   panic(2)
case 3:
   panic(3)
}

All the code blocks have the same indentation.

Ian Lance Taylor

unread,
Aug 24, 2015, 8:36:43 PM8/24/15
to Michael Whatcott, golang-nuts
On Mon, Aug 24, 2015 at 12:27 PM, Michael Whatcott <mdwha...@gmail.com> wrote:
>
> Why aren't the `case` and `default` statements within switch statements
> similarly indented?

Case labels in a switch are handled like regular labels (that is,
targets of a goto statement).

Ian
Reply all
Reply to author
Forward
0 new messages