Go - 轉到語句



Go 程式語言中的 goto 語句從 goto 無條件跳轉到同一函式中的標記語句。

注意 − 強烈不建議在任何程式語言中使用 goto 語句,因為它會使程式難以跟蹤控制流,程式難以理解且修改工作量大。可以使用其他構造重寫使用 goto 的任何程式。

語法

Go 中 goto 語句的語法如下所示 −

goto label;
..
.
label: statement;

在此處,label 可以是除 Go 關鍵字以外的任何純文字,並且可以在 goto 語句上方或下方 Go 中的任何位置進行設定。

流程圖

Go goto statement

示例

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
go_loops.htm
廣告
© . All rights reserved.