Control Structures
for
Go 只有一種迴圈 for。
//1
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum) //45
//2
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum) //1024
//3
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum) //1024
//4
var m map[string]int
m = make(map[string]int)
m["route"] = 66
for key, value := range m {
fmt.Println("Key:", key, "Value:", value)
}
if
//1
if i % 2 == 0 {
// even
} else {
// odd
}
//2
if i % 2 == 0 {
// divisible by 2
} else if i % 3 == 0 {
// divisible by 3
} else if i % 4 == 0 {
// divisible by 4
}
switch
如同其他語言。
switch i {
case 0: fmt.Println("Zero")
case 1: fmt.Println("One")
case 2: fmt.Println("Two")
case 3: fmt.Println("Three")
case 4: fmt.Println("Four")
case 5: fmt.Println("Five")
default: fmt.Println("Unknown Number")
}
goto
Go 語言跟 C 語言一樣也有goto。
i := 0
HERE:
fmt.Print(i)
i++
if i < 10 {
goto HERE
}