go流程控制

go中的流程控制和PHP类似主要包含以下几种:

  • if,if else,else if
  • switch,case,select
  • for,range
  • goto

if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import "fmt"

func () {
score := 100

if score > 90 {
fmt.Println("A")
} else if score > 80 {
fmt.Println("B")
} else if score > 70 {
fmt.Println("C")
} else if score > 60 {
fmt.Println("D")
} else {
fmt.Println("E")
}
}

与PHP相比,不同的地方:

  • 条件语句不需要使用圆括号
  • {}必须存在
  • 左花括号{必须与if或者else同一行
  • if之后,条件语句之前,可以添加变量初始化,例如if i:=10;i<10{}

switch

1
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
package main

import "fmt"

func () {
score := 100

switch {
case score >= 90:
fmt.Println("Grade: A")
case score >= 80 && score < 90:
fmt.Println("Grade: B")
case score >= 70 && score < 80:
fmt.Println("Grade: C")
case score >= 60 && score < 70:
fmt.Println("Grade: D")
default:
fmt.Println("Grade: F")
}


switch score {
case 90, 100:
fmt.Println("Grade: A")
case 80:
fmt.Println("Grade: B")
case 70:
fmt.Println("Grade: C")
case 60:
//此时表示 60,65 执行同一个逻辑 区别于PHP,必须增加fallthrough关键字
fallthrough
case 65:
fmt.Println("Grade: D")
default:
fmt.Println("Grade: F")
}
}