Go語言之循環與條件判斷


一、for循環

Go 語言中沒有 while 循環,只有一個 for 循環

for 變量初始化;條件;變量自增/自減 {
    循環體內容
}

1、基本使用

for i := 0; i < 10; i++ {
   fmt.Println(i)
}

2、省略第一部分

i := 0
for ; i < 10; i++ {
   fmt.Println(i)
}

3、省略第一和三部分(這是一個 while 循環) for 條件 { 循環體內容 }

i := 0
for i < 10 {
   fmt.Println(i)
   i++
}

4、死循環

for	{
    fmt.Println("死循環")
}

5、開多協程演示

for i := 0; i < 2000; i++ {
   go test()
}

func test() {
	for {
		fmt.Println("死循環")
	}
}

6、break:結束本次 for 循環,continue 結束本次循環,繼續下一次循環

二、Switch語句

Switch 是一個條件語句,用於將表達式的值與可能匹配的選項列表進行比較,並根據匹配情況執行相應的代碼塊,它可以被認為是替代多個 if else 語句的常用方式

1、基本使用

num := 4
switch num {
case 1:
   fmt.Println("1")
case 2:
   fmt.Println("2")
case 3:
   fmt.Println("3")
case 4:
   fmt.Println("4")
}

// 輸出
4

2、默認情況(都沒有匹配上)

num := 5
switch num {
case 1:
   fmt.Println("1")
case 2:
   fmt.Println("2")
case 3:
   fmt.Println("3")
case 4:
   fmt.Println("4")
default:
   fmt.Println("都沒有匹配上")
}

// 輸出
都沒有匹配上

3、多表達式判斷

num := 44
switch num {
case 11, 12, 13, 14:
   fmt.Println("1")
case 21, 22:
   fmt.Println("2")
case 31, 33:
   fmt.Println("3")
case 40, 43, 44:
   fmt.Println("4")
default:
   fmt.Println("都沒有匹配上")
}

// 輸出
4

4、無表達式的 Switch

num := 44
switch {
case num == 11, num == 12:
   fmt.Println(11, 12)
case num == 40, num == 44:
   fmt.Println(40, 44)
}

// 輸出
40 44

5、Fallthrough(穿透,只要看到 fallthrough,無條件執行下一個 case 或者 default )

num := 12
switch {
case num == 11, num == 12:
   fmt.Println(11, 12)
   fallthrough
case num == 40, num == 44:
   fmt.Println(40, 44)
   fallthrough
default:
   fmt.Println("無匹配")
}

// 輸出
11 12
40 44
無匹配


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM