題名の通り、Go言語のswitch文は暗黙でcaseの最後にbreakが入ります。
なので
i := 1 switch i { case 1: fmt.Println("1") case 2: fmt.Println("2") default: fmt.Println("other") }
と書くとcase 1
にマッチし、case 2
には入りません。
fallthrough
逆にcase 1
にマッチした後にcase 2
も実行したい場合にはfallthrough
を利用するようです。
i := 1 switch i { case 1: fmt.Println("1") fallthrough case 2: fmt.Println("2") default: fmt.Println("other") }
こんな感じですね。