Skip to content
目录

Go 语言笔记:跳转语句

跳转语句

goto 语句是 Go 语言中的跳转语句,后面紧跟一个标签,该标签代表一个代码段的执行起点。

go
goto label
...
label code
go
package main

import "fmt"

func main() {
  fmt.Println("Winter is coming.")
  goto label
  fmt.Println("Winter is coming.")
  label:
    fmt.Println("Summer is coming.")
}

// 打印结果
Winter is coming.
Summer is coming.

条件限制

goto 语句和标签之间不能存在变量的定义,否则会编译报错

go
package main

import "fmt"

func main() {
  fmt.Println("Winter is coming.")
  goto label
  num := 10
  fmt.Println(num)
  label:
    fmt.Println("Summer is coming.")
}

// 报错信息
./main.go:7:7: goto label jumps over declaration of num at ./main.go:8:6

TIP

goto 语句可以配合其他条件实现类似 breakcontinue 等效果。


Released under the MIT License.