4.4 Go goto continue break
Go language goto statement unconditional jump to a specified line of code.
goto statement is generally used in combination with conditional statements, conditions to achieve escape out of the loop and the like.
Go program 不推荐使用goto
, so as to avoid procedural confusion, difficult to read.
Example:
package main import "fmt" func main() { var num int = 100 fmt.Println("num值100") if num > 90 { goto label //此处代码已经不走,直接goto了 fmt.Println("呵呵") } fmt.Println("我是占位符") fmt.Println("我是占位符") fmt.Println("我是占位符") fmt.Println("我是占位符") fmt.Println("我是占位符") //触发了goto,进入本次标签 label: fmt.Println("由于触发了goto,进入到我这里了") fmt.Println("我也是占位符") fmt.Println("我也是占位符") fmt.Println("我也是占位符") }
1.1. break
For 中断当前循环
or跳出switch中的case语句
package main import "fmt" func main() { var num int = 10 for num < 50 { fmt.Printf("a的值是:%v\n", num) num++ if num > 30 { break //跳出for循环 } } }
break label
When the for-loop is nested, nested directly out all cycles can be used to break label characteristic
package main import ( "fmt" ) func main() { fmt.Println("主程序开始执行") Exit: for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { if i+j > 15 { fmt.Println("程序结束") break Exit } } } fmt.Println("已跳出循环体") }
1.2. Continue statement
continue statement residual bit out of the current cycle, the next cycle continues.
package main import "fmt" func main() { /* 定义局部变量 */ var a int = 10 /* for 循环 */ for a < 20 { if a == 15 { /* 当a等于15时,跳出循环,让a++,等于16,跳过本次循环 */ a++ continue } fmt.Printf("a 的值为 : %d\n", a) a++ } }
1.3. Return statement
return used in the method or function, or a method where the termination represents a function (method and function).
return in the main function, the main function indicates the termination, the termination procedure.
package main import "fmt" func main() { for i := 0; i <= 10; i++ { if i == 5 { return //直接退出main函数了 } fmt.Printf("本次循环次数:%d\n", i) } //永远走不带这里了,第五次for循环时候,直接return了 fmt.Println("循环结束,走到了我") }