GO(3) - control flow
簡單地介紹一下 Go 中 control flow 的寫法。
1. if 條件式:
輸入參數,並判斷是否在特定範圍內。
package main
import (
"flag"
"fmt"
)
func main() {
agePtr := flag.Int("age", 1, "user age")
flag.Parse()
age := *agePtr
fmt.Println("age:", age)
if age < 10 {
fmt.Println("Very young")
} else if age >= 10 && age <= 30 {
fmt.Println("Yong")
} else {
fmt.Println("Old")
}
}
另一種很常出現的寫法是在 if 判斷時生成一個新的區域變數,再對該區域變數做判斷 (如: line := file.Read)。
package main
import "fmt"
func main() {
file := "Hello world"
if line := file; len(line) != 0 {
fmt.Println(line)
}
}
2. switch 條件式:
切換各個條件。
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Print("Do you like cat(0) or dog(1):")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
fmt.Println(input)
switch input {
case "0":
fmt.Println("Cat!!")
case "1":
fmt.Println("Dog!!")
default:
fmt.Println("??")
}
}
一次比對多個條件。
func main() {
input := "3"
switch input {
case "0", "1", "2":
fmt.Println("0 1 2 !!")
case "3", "4", "5":
fmt.Println("3 4 5")
default:
fmt.Println("??")
}
}
3. for 迴圈:
傳統 for 類似 C 的寫法。
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
fmt.Println("i:", i)
}
}
while loop 等於沒有條件的 for。
package main
import "fmt"
func main() {
count := 0
for {
fmt.Println("count:", count)
count += 1
if count > 10 {
break
}
}
}
用 range 迭代回傳 index 及 item。
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4}
for idx, it := range arr {
fmt.Printf("idx: %d, it: %d\n", idx, it)
}
}

留言
張貼留言