天天看點

Go 中 while 和 do..while 的實作一 點睛二 while 循環的實作三 do..while 的實作

一 點睛

Go 語言沒有 while 和 do...while 文法,這一點和其他語言不同,需要格外注意一下,如果需要使用類似其它語言(比如 java / c 的 while 和 do...while ),可以通過 for  循環來實作其使用效果。

二 while 循環的實作

1 圖解

Go 中 while 和 do..while 的實作一 點睛二 while 循環的實作三 do..while 的實作

2 說明

a for 循環是一個無限循環。

b break 語句用來跳出 for 循環。

3 實戰

a 需求 

使用上面的 while 實作完成輸出10 句"hello,world”.

b 代碼

package main

import "fmt"

func main() {
   // 使用while方式輸出10句 "hello,world"
   // 循環變量初始化
   var i int = 1
   for {
      if i > 10 { // 循環條件
         break // 跳出for循環,結束for循環
      }
      fmt.Println("hello,world", i)
      i++ // 循環變量的疊代
   }

   fmt.Println("i=", i)
}           

c 測試

hello,world 1
hello,world 2
hello,world 3
hello,world 4
hello,world 5
hello,world 6
hello,world 7
hello,world 8
hello,world 9
hello,world 10
i= 11           

三 do..while 的實作

1 圖解

Go 中 while 和 do..while 的實作一 點睛二 while 循環的實作三 do..while 的實作

2 說明

a 上面的循環是先執行,再判斷,是以至少執行一次。

b 當循環條件成立後,就會執行 break, break 用來跳出 for 循環,結束循環。

3 實戰

a 需求

使用上面的 do...while 完成輸出10 句"hello,ok"。

b 代碼

package main

import "fmt"

func main() {
   // 使用的 do...while 完成輸出10句”hello,ok“
   var j int = 1
   for {
      fmt.Println("hello,ok", j)
      j++ // 循環變量的疊代
      if j > 10 {
         break // break 就是跳出for循環
      }
   }
}           

c 測試

hello,ok 1
hello,ok 2
hello,ok 3
hello,ok 4
hello,ok 5
hello,ok 6
hello,ok 7
hello,ok 8
hello,ok 9
hello,ok 10           
go