流程控制
If/Else 分支
Section titled “If/Else 分支”package main
import "fmt"
func main() { young(20) isUsingNewVariable(100, 200)}
func young(age int) { if age < 18 { println("I am a child") } else if age > 18 && age < 30 { println("I am young") } else { println("I am old") }}
func isUsingNewVariable(start int, end int) { if distance := end - start; distance > 100 { fmt.Printf("Too far away :%d\n", distance) } else { fmt.Printf("short away: %d\n", distance) }
// 这里不能访问 distance //fmt.Printf("distance: %d\n", distance)}For 循环
Section titled “For 循环”package main
import "fmt"
func main() {
i := 1 for i <= 3 { fmt.Println(i) // 1 2 3 i = i + 1 }
for j := 7; j <= 9; j++ { fmt.Println(j) // 7 8 9 }
for { fmt.Println("loop") // loop break // 跳出循环 }
for n := 0; n <= 5; n++ { if n%2 == 0 { continue // 直接进入下一次循环 } fmt.Println(n) // 1 3 5 }}func forI() { arr := []int{10, 20, 30, 40, 50} for i := 0; i < len(arr); i++ { fmt.Printf("index: %d, value: %d\n", i, arr[i]) }}
func forR() { arr := []int{1, 2, 3, 4, 5} for index, value := range arr { fmt.Printf("index: %d, value: %d\n", index, value) }
// 只需要value for _, v := range arr { fmt.Printf("value: %d\n", v) }
// 只需要index,建议用fori for index := range arr { fmt.Printf("index: %d\n", index) }}Switch 分支结构
Section titled “Switch 分支结构”package main
import ( "fmt" "time")
func main() { i := 2 fmt.Print("write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") // Write 2 as two case 3: fmt.Println("three") default: fmt.Println("other") }
t := time.Now() switch { case t.Hour() < 12: fmt.Println("It's before noon") default: fmt.Println("It's after noon") }}Select
Section titled “Select”package main
import ( "time")
func main() { ch1 := make(chan string) ch2 := make(chan string)
go func() { time.Sleep(time.Second * 2) ch1 <- "message from channel1" }()
go func() { time.Sleep(time.Second) ch2 <- "message from channel2" }()
// select 同时的情况下,顺序是随机的 for i := 0; i < 2; i++ { select { case msg := <-ch1: println(msg) case msg := <-ch2: println(msg) case <-time.After(time.Second * 2): println("timeout") } }}