在 Go 中,我们使用 while 循环 来执行一段代码,直到满足某个特定条件为止。
与许多其他编程语言不同,Go 没有专门的 while 循环关键字。但是,我们可以使用 for
循环来实现 while 循环的功能。
Go while 循环语法
for condition {
// code block
}
在此,循环会评估 condition
。如果条件为
true
- 则执行循环内的语句,并再次评估condition
false
- 则循环终止
Go 中 while 循环的流程图

示例:Go while 循环
// Program to print numbers between 1 and 5
package main
import ("fmt")
func main() {
number := 1
for number <= 5 {
fmt.Println(number)
number++
}
}
输出
1 2 3 4 5
在这里,我们将 number 初始化为 1。
- 在第一次迭代中,条件
number <= 5
为true
。因此,将 1 打印到屏幕上。现在,number 的值增加到 2。 - 再次测试条件
number <= 5
为 true。因此,2 也被打印到屏幕上,并且 number 的值增加到 3。 - 此过程一直持续到 number 变为 6。然后,条件
number <= 5
将为false
,循环终止。
使用 while 循环创建乘法表
// Program to create a multiplication table of 5 using while loop
package main
import ("fmt")
func main() {
multiplier := 1
// run while loop for 10 times
for multiplier <= 10 {
// find the product
product := 5 * multiplier
// print the multiplication table in format 5 * 1 = 5
fmt.Printf("5 * %d = %d\n", multiplier, product)
multiplier++
}
}
输出
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50
在这里,我们将 multiplier := 1
初始化。在每次迭代中,multiplier 的值会增加 1,直到 multiplier <= 10
。
Go do...while 循环
在 Go 中,我们可以使用相同的 for
循环来实现 do while 循环 的功能。例如:
// Program to print number from 1 to 5
package main
import "fmt"
func main(){
number := 1
// loop that runs infinitely
for {
// condition to terminate the loop
if number > 5 {
break;
}
fmt.Printf("%d\n", number);
number ++
}
}
输出
1 2 3 4 5
请注意 for
循环内的 if
语句。
if number > 5 {
break;
}
此语句充当 do...while 循环 中的 while 子句,用于终止循环。