Go - break 語句



Go 程式語言中的 break 語句有兩個用途 −

  • 如果迴圈內遇到 break 語句,則迴圈將立即終止,並且程式控制將恢復到迴圈後面的下一條語句。

  • 它可用於終止 switch 語句中的 case。

如果你正在使用巢狀迴圈,則 break 語句將停止執行最內層迴圈,並開始執行程式碼塊後的下一行程式碼。

語法

Go 中 break 語句的語法如下 −

break;

流程圖

Go break statement

示例

package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 10

   /* for loop execution */
   for a < 20 {
      fmt.Printf("value of a: %d\n", a);
      a++;
      if a > 15 {
         /* terminate the loop using break statement */
         break;
      }
   }
}

當編譯並執行以上程式碼時,它將產生以下結果 −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
go_loops.htm
廣告
© . All rights reserved.