寝ても覚めてもこんぴうた

プログラム書いたり、ネットワーク設計したり、サーバ構築したり、車いじったり、ゲームしたり。そんなひとにわたしはなりたい。 投げ銭は kyash_id : chidakiyo マデ

Golangのswitch文は暗黙でcaseの最後にbreakが入る

題名の通り、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")
}

こんな感じですね。