Go for循环语句实例

for语句是Go编程语言中唯一的循环结构。这里有三种基本类型的for循环。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

  1. 最基本的类型,只具有单一条件。
  2. 一个经典的初始化/条件/之后的for循环。
  3. 对于没有条件的函数将重复循环,直到跳出循环或从包闭函数中返回。

也可以继续下一个循环的迭代。

for.go的完整代码如下所示 -

// `for` is Go's only looping construct. Here are
// three basic types of `for` loops.

package main

import "fmt"

func main() {

    // The most basic type, with a single condition.
    i := 1
    for i <= 3 {
        fmt.Println(i)
        i = i + 1
    }

    // A classic initial/condition/after `for` loop.
    for j := 7; j <= 9; j++ {
        fmt.Println(j)
    }

    // `for` without a condition will loop repeatedly
    // until you `break` out of the loop or `return` from
    // the enclosing function.
    for {
        fmt.Println("loop")
        break
    }

    // You can also `continue` to the next iteration of
    // the loop.
    for n := 0; n <= 5; n++ {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run for.go


7

loop



上一篇:Go常量实例

下一篇:Go if/else语句实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程