Golang初级系列教程-控制结构-for-break-continue-range

Golang初级系列教程-控制结构-For/break/continue/range

for 语句是 Go唯一的循环语句。通用语句定义如下:


*for “initialization statements”; “bool expression that has to evaluate to true”; “statements run prior to every loop except the first” {
//code to be executed if the boolean expression evaluates to true
}*

for 语句中三部分中的任意一部分都可以没有内容,但是分号必须存在(除非三部分全部没有,这时分号也可以不要),最好的方式就是实践喽,运行如下代码。

package main

import "fmt"

func main() {
    // initialize i to 0; check each time that i is less than 5; increment i for each loop after the first
    for i := 0; i < 5; i++ {
        fmt.Println("Value of i is now:", i)
    }
}
Value of i is now: 0
Value of i is now: 1
Value of i is now: 2
Value of i is now: 3
Value of i is now: 4

以下代码片段都是有效的语言,依次可以验证上述内容。

//prints increasing value of i infinitely, since the middle check statement does not exist
for i := 0; ; i++ {
    fmt.Println("Value of i is now:", i)
}

//prints "value of i is: 0" infinitely since the incrementing part is not there and i can never reach 3
for i := 0; i < 3;  {
    fmt.Println("Value of i:", i)
}

//here both initialization and incrementing is missing in the for statement, but it is managed outside of it
s := ""
for ; s != "aaaaa";  {
    fmt.Println("Value of s:", s)
    s = s + "a"
}

通过运用多赋值模式(i, j = i + 2, j + 2),在 for 语句中,可以使用多个赋值语句,同样可以递增或者更新多个变量的值。
在其它语言中,可以通过 , 实现,但是请注意,在 Go 中不允许这样的语句。

package main

import "fmt"

func main() {
    //multiple initialization; a consolidated bool expression with && and ||; multiple ‘incrementation’
    for i, j, s := 0, 5, "a"; i < 3 && j < 100 && s != "aaaaa"; i, j, s = i+1, j+1, s + "a"  {
        fmt.Println("Value of i, j, s:", i, j, s)
    }
}

Value of i, j, s: 0 5 a
Value of i, j, s: 1 6 aa
Value of i, j, s: 2 7 aaa

break关键字

break 关键字可以在当前位置终止循环,并继续在 for 结束的位置继续执行之后的语句。在下面简单的例子中,我们在遇到一个特定的条件之后使用 break 语句。由于 for 语句没有判定条件,如果不执行 break,将会陷入无限循环。注意:break 不会终止程序的运行,只是跳出循环,继续执行 } 之后的语句。

package main

import "fmt"

func main() {
    i := 0
    for { //since there are no checks, this is an infinite loop
        if i >= 3 { break } //break out of this for loop when this condition is met
        fmt.Println("Value of i is:", i)
        i++;
    }
    fmt.Println("A statement just after for loop.") 
}
Value of i is: 0
Value of i is: 1
Value of i is: 2
A statement just after for loop.

continue 关键字

continue 是让程序重新从 for 循环的开始处执行。条件判定和自增部分都会执行,也就是说进入了下一次的迭代循环。也表现为跳过了 continue 之后的语句,而直接进入下一次循环。

在下面的例子中,使用 continue 语句只把奇数打印出来。当遇到一个偶数(i20),跳过打印输出语句,并且开始执行下一次循环。

package main

import "fmt"

func main() {

    //a continue within this loop will bring back execution to the beginning of the loop.  Checks and increments in for loop will be executed.

    for i := 0; i<7 ; i++ { //control comes back here when there is a ‘continue’ within this for block
        if i%2 == 0 { 
            continue //if it is an even number, go back to beginning of for loop
        }
        fmt.Println("Odd:", i)  //execution will reach here only when i%2 is not 0, and therefore it is odd
    }
}
Odd: 1
Odd: 3
Odd: 5

range 关键字

range 关键字用来遍历 listarray 或者 map。为了方便理解,可以认为 range 等效于 for earch index of。对于 arrays 或者 slices, 将会返回整型的下标;对于 map,将会返回下一个键值对的 key。 支持返回单值或者两个值, 如果返回一个值,那么为下标,否则为下标和下标所对应的值。

package main

import "fmt"

func main() {
    //on an array, range returns the index
    a := [...]string{"a", "b", "c", "d"}
    for i := range a {
        fmt.Println("Array item", i, "is", a[i])
    }

    //on a map, range returns the key 
    capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
    for key := range capitals {
        fmt.Println("Map item: Capital of", key, "is", capitals[key])
    }

    //range can also return two items, the index/key and the corresponding value 
    for key2, val := range capitals {
        fmt.Println("Map item: Capital of", key2, "is", val)
    }
}
Array item 0 is a
Array item 1 is b
Array item 2 is c
Array item 3 is d
Map item: Capital of Japan is Tokyo
Map item: Capital of Italy is Rome
Map item: Capital of France is Paris
Map item: Capital of Japan is Tokyo
Map item: Capital of Italy is Rome
Map item: Capital of France is Paris

Golang一种神奇的语言,让我们一起进步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值