go 的程序控制大致分成三種 if for case 語句
1、 if 循環
if-else 語句之間可以有任意數量的 else if。
條件判斷順序是從上到下。如果 if 或 else if 條件判斷的結果爲真,則執行相應的代碼塊。 如果沒有條件爲真,則 else 代碼塊被執行。
語法結構
if condition{
}else if condition{
}else{
}
定義示列
package main
import "fmt"
func iftest() {
score :=61
if score > 60{
fmt.Println("成績合格")
} else if score >90{
fmt.Println("成績優秀")
}else if score<0 {
fmt.Println("成績不能爲負數")
}else if score < 60 {
fmt.Println("成績不合格")
} else{
fmt.Println("成績不合法")
}
}
func main() {
iftest()
// 輸出
成績合格
}
2、for 循環
go 循環只有一種叫做for
語法結構
for initialisation; condition; post {
}
初始化語句只執行一次。循環初始化後,將檢查循環條件。如果條件的計算結果爲 true ,則 {} 內的循環體將執行,
接着執行 post 語句。post 語句將在每次成功循環迭代後執行。在執行 post 語句後,條件將被再次檢查。
如果爲 true, 則循環將繼續執行, 否則 for 循環將終止。
示列
package main
import "fmt"
func fortest1() {
for i :=1;i <=10;i++{
fmt.Println(i)
}
}
// 輸出
1
2
3
4
5
6
7
8
9
10
//在 go 中 break語句在完成執行之前突然終止for 循環,之後程序將會在for 循環下開始下一行
代碼開始執行
for i:=2; i<=20 ;i+=2{
if i >8{
break
}
fmt.Printf("%d",i)
}
fmt.Printf("\nline after for loop")
// 輸出 當 i的值大於8後, fmt.Printf("%d",i) ,就終止執行了,執行最後一個fmt.Print
2468
line after for loop
// continue
continue 語句用來跳出 for 循環中當前循環,
在 continue 語句後的所有的 for 循環語句都不會在本次循環中執行。循環體會在一下次循環中繼續執行。
for i :=1;i<=10;i++{
if i%2 ==0{
continue
}
fmt.Printf("%d",i)
}
}
// 輸出 ,當於爲0 的不輸出
13579
func main() {
fortest1()
}
// go 的無限循環語句
for {
fmt.Println("Hello World")
}
3、switch 語句
switch 語句用於基於不同條件執行不同動作,每個case 分之都是唯一的,從上至下逐以測試,直到匹配爲止
switch 語句的執行過程從上至下,直到找到匹配項,匹配項後面也不需要加break
switch 默認情況下case 最後帶break 語句,匹配成功後不會執行其他case,可以使用fallthrough
語法結構如下
switch var1 {
case val1:
...
case val2:
...
default:
...
}
package main
import "fmt"
func switchtest1() {
var scores int = 90
switch scores{
case 90:
fmt.Println("very good score")
fallthrough
case 80:
fmt.Println("good score")
case 60:
fmt.Println("just ok")
}
}
輸出 ,當在case 90 條件下新增 fallthrough 時,case 80 的條件也會輸出
good score
very good score
func main() {
switchtest1()
}