欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Golang break/continue label

程序员文章站 2024-03-23 18:24:10
...

break用来结束最里面的for/select/switch的语句,如果这里有标签,那么它必须在for/select/switch的正上面。

http://localhost:6060/ref/spec#Break_statements

这也就是说,假如你有类似如下的代码:

    for i = 0; i < n; i++ {
        for j = 0; j < m; j++ {
            switch a[i][j] {
            case nil:
                state = Error
                break OuterLoop
            case item:
                state = Found
                break
            }
        }
    }

在switch里面使用break,那只是结束switch的语句,并不会跳出for循环。如果想跳出for循环,改为如下:

OuterLoop:
    for i = 0; i < n; i++ {
        for j = 0; j < m; j++ {
            switch a[i][j] {
            case nil:
                state = Error
                break OuterLoop
            case item:
                state = Found
                break OuterLoop
            }
        }
    }

另, continue 也可以配合label,与break对比如下:

package main

import (
    "fmt"
)

func main() {
    FirstNames := []string{"aaa", "bbb", "ccc"}
    LastNames := []string{"111", "222", "333"}

Loop:
    for _, firstName := range FirstNames {
        for _, lastName := range LastNames {
            fmt.Printf("Name: %s %s\n", firstName, lastName)

            if firstName == "bbb" && lastName == "111" {
                break Loop
            }
        }
    }
    println("Over.")
}

输出:

Name: aaa 111
Name: aaa 222
Name: aaa 333
Name: bbb 111
Over.

continue label

func main() {
    FirstNames := []string{"aaa", "bbb", "ccc"}
    LastNames := []string{"111", "222", "333"}

Loop:
    for _, firstName := range FirstNames {
        for _, lastName := range LastNames {
            fmt.Printf("Name: %s %s\n", firstName, lastName)

            if firstName == "bbb" && lastName == "111" {
                continue Loop
            }
        }
    }
    println("Over.")
}

输出:

Name: aaa 111
Name: aaa 222
Name: aaa 333
Name: bbb 111
Name: ccc 111
Name: ccc 222
Name: ccc 333
Over.