介绍go中的流程控制语句: for, if/else, switch
For
for是 Go 唯一的循环结构, 以下是一些基本的循环类型for:
for.go1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| package main
import ( "fmt" )
func main() { i := 1 for i <= 3 { fmt.Println(i) i++ } for j := 4; j <= 6; j++ { fmt.Println(j) } for i := range 3 { fmt.Println("range", i) } for { fmt.Println("loop") break } for n := range 6 { if n%2 == 0 { continue } fmt.Println(n) } }
|
log1 2 3 4 5 6 7 8 9 10 11 12 13 14
| $ go run for.go 1 2 3 0 1 2 range 0 range 1 range 2 loop 1 3 5
|
If/Else
Go 中没有三元操作符(a ? b : c), 因此即使对于基本条件, 也需要使用完整的语句。Go 中的条件不需要括号,但大括号是必需的, 以下是一些基本的 if/else 条件语句示例:
if-else.go1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package main
import ( "fmt" )
func main() { if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") } if 8%4 == 0 { fmt.Println("8 is divisible by 4") } if 8%2 == 0 || 7%2 == 0 { fmt.Println("either 8 or 7 are even") } if num := 1; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digit") } }
|
log1 2 3 4 5
| $ go run if-else.go 7 is odd 8 is divisible by 4 either 8 or 7 are even 9 has 1 digit
|
Switch
switch 语句是跨多个分支的条件, Go 只会运行选定的 case, 而非之后所有的 case。在效果上,Go 的做法相当于这些语言中为每个 case 后面自动添加了所需的 break 语句, 除非以 fallthrough 语句结束, 否则分支会自动终止:
switch.go1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package main
import ( "fmt" "time" )
func main() { i := 1 fmt.Print("Write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") case 3: fmt.Println("three") } switch time.Now().Weekday() { case time.Saturday, time.Sunday: fmt.Println("it's weekend") default: fmt.Println("it's not weekend") } now := time.Now() switch { case now.Hour() < 12: fmt.Println("am") default: fmt.Println("pm") } what_type := func(i interface{}) { switch t := i.(type) { case int: fmt.Printf("type of %d: int", t) case string: fmt.Printf("type of %v: string", t) default: fmt.Println("none") } } what_type("1") what_type(1) }
|
log1 2 3 4 5 6 7
| $ go run switch.go Write 2 as two It's a weekday It's after noon I'm a bool I'm an int Don't know type string
|
参考链接