天天看点

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