Go の制御構文
Go の if 文、switch 文、for 文
if 文
if 条件 { 処理 } は、条件が真の場合だけ処理を実行する。
条件を丸かっこ((...))で囲む必要はないが、処理は波かっこ({ ... })で囲む必要がある。
if x > y {
fmt.Println("x is greater than y")
}
else または else if も使用できる。
if x > y {
fmt.Println("Big")
} else if x < y {
fmt.Println("Small")
} else {
fmt.Println("Equal")
}
switch 文
switch 式 { ... } は、式の値に応じて処理を分岐する。
switch mode {
case "running":
fmt.Println("実行中")
case "stop":
fmt.Println("停止中")
default:
fmt.Println("不明")
}
switch { ... } では、各 case に条件を記述できる。
switch {
case x > y:
fmt.Println("Big")
case x < y:
fmt.Println("Small")
default:
fmt.Println("Equal")
}
ほかの多くの言語とは異なり、break 文は不要である。次の case の処理も続けて実行するには fallthrough を使う。
次の例では、dayOfWeek が "Sat" または "Sun" の場合に "Holiday" を出力する。
switch dayOfWeek {
case "Sat":
fallthrough
case "Sun":
fmt.Println("Holiday")
default:
fmt.Println("Weekday")
}
for 文
Go には while 文がない。すべての繰り返し処理に for を使う。
次の例では、x が y より小さい間、処理を繰り返す。
for x < y {
x++
}
for 初期化; 条件; 後処理 { 処理 } は、最初に初期化を行い、条件が真の間は処理と後処理を繰り返す。
for i := 0; i < 10; i++ {
fmt.Println(i)
}
条件を省略すると無限ループになる。continue は次の繰り返しを開始し、break はループから抜ける。
package main
import "fmt"
func main() {
n := 0
for {
n++
if n > 10 {
break
} else if n%2 == 1 {
continue
} else {
fmt.Println(n)
}
}
}
実行結果:
2
4
6
8
10
配列やスライスなどを処理する場合は、range を使って繰り返すことができる。
package main
import "fmt"
func main() {
colors := [...]string{"Red", "Green", "Blue"}
for i, color := range colors {
fmt.Printf("%d: %s\n", i, color)
}
}
実行結果:
0: Red
1: Green
2: Blue