DEV Community

indiewebdev
indiewebdev

Posted on

Golang Notes - 13

Labels

  • used in break, continue, goto statements

  • not block scoped, live in another space

  • used to terminate outer enclosing loops

func main() {
outer:
    for i := 0; i < 10; i++ {
        for j := 0; j < 10; j++ {
            fmt.Println(i, j)
            if i == j {
                break outer
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Goto
goto statement jump to label

func main() {
    i := 0
loop:
    if i < 10 {
        fmt.Println(i)
        i++
        goto loop
    }
}
Enter fullscreen mode Exit fullscreen mode

it is not allowed to jump to label after new variable have been introduced

goto todo // Not valid
    x := 10
    fmt.Println(x)

todo:
   fmt.Println("todo")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)