if文と似ていますが、条件分岐が3つ以上ある場合には、
switchを利用すると見やすくなるかもしれません。
choice := "イタリアン"
switch choice {
case "和":
fmt.Println("rice")
case "洋":
fmt.Println("bread")
case "中":
fmt.Println("noodle")
default:
fmt.Println("undefined") // undefined
}
どの条件にも該当しない場合は、defaultに、
defaultも記載がない場合は、どの処理も行われません。
判定対象を、switch内でのみ通用する変数とすることも可能です。
caseの処理内で、その変数を使用することもできます。
func getChoice() string {
return "洋"
}
func main() {
switch choice := getChoice(); choice {
case "和":
fmt.Println("rice")
case "洋":
fmt.Println(choice, "bread") // 洋 bread
case "中":
fmt.Println("noodle")
default:
fmt.Println("undefined")
}
}
式で条件を評価したい場合には、switchの記載を簡略化する事ができます。
t := time.Now() // 現在時刻を取得
switch {
case t.Hour() < 12:
fmt.Println("Morning")
case t.Hour() < 17:
fmt.Println("Afternoon")
case t.Hour() < 24:
fmt.Println("Night")
default:
fmt.Println("undefined")
}