Go - goto 语句
Go 编程语言中的 goto 语句提供从 goto 无条件跳转到同一函数中的标签语句。
注意 − 在任何编程语言中都强烈不鼓励使用 goto 语句,因为它会使程序的控制流难以追踪,导致程序难以理解和修改。任何使用 goto 的程序都可以使用其他结构重写。
语法
Go 中 goto 语句的语法如下 −
goto label; .. . label: statement;
这里,label 可以是除 Go 关键字外的任意纯文本,并且可以在 Go 程序中 goto 语句的上方或下方任何位置设置。
流程图
示例
package main
import "fmt"
func main() {
/* 本地变量定义 */
var a int = 10
/* 执行循环 */
LOOP: for a < 20 {
if a == 15 {
/* 跳过本次迭代 */
a = a + 1
goto LOOP
}
fmt.Printf("value of a: %d\n", a)
a++
}
}
上述代码编译并执行后,会产生以下结果 −
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19