目录

goto statement

Go编程语言中的goto语句提供了从goto到同一函数中带标签语句的无条件跳转。

Note - 在任何编程语言中都不鼓励使用goto语句,因为很难跟踪程序的控制流程,使程序难以理解且难以修改。 任何使用goto的程序都可以使用其他构造重写。

语法 (Syntax)

Go中goto语句的语法如下 -

goto label;
..
.
label: statement;

这里, label可以是除Go关键字之外的任何纯文本,并且可以在Go程序的上方或下方的任何位置设置为goto语句。

流程图 (Flow Diagram)

go_goto_statement

例子 (Example)

package main
import "fmt"
func main() {
   /* local variable definition */
   var a int = 10
   /* do loop execution */
   LOOP: for a < 20 {
      if a == 15 {
         /* skip the iteration */
         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
↑回到顶部↑
WIKI教程 @2018