Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go for循环语句实例
Go for循环语句实例
作者:--    发布时间:2019-11-20

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

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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
1
2
3
7
8
9
loop
1
3
5

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册