Jump statement is a common flow control statement in programming languages, used to change the order of program execution. In Go language, there are three main types of jump statements:break
,continue
andgoto
. This article will delve into the specific usage of these jump statements in the Go language, and attach corresponding code examples.
break
statement is used to jump out of the current loop or the execution of theswitch
statement and terminate the subsequent code block. The following is an example of using thebreak
statement in afor
loop:
package main import "fmt" func main() { for i := 1; i <= 5; i++ { if i == 3 { break } fmt.Println(i) } }
In the above code, when the value ofi
is equal to 3, execute Thebreak
statement breaks out of the loop, so only1
and2
will be output.
continue
statement is used to skip the remaining code in the current loop and directly enter the next cycle. The following is an example of using thecontinue
statement in afor
loop:
package main import "fmt" func main() { for i := 1; i <= 5; i++ { if i == 3 { continue } fmt.Println(i) } }
In the above code, when the value ofi
is equal to 3, execute Thecontinue
statement skips the code in the current loop and directly enters the next cycle, so only1
,2
,4
will be output. and5
.
The goto
statement can unconditionally transfer to another location in the program, usually used to jump to a label. The following is an example of using thegoto
statement:
package main import "fmt" func main() { i := 1 start: fmt.Println(i) i++ if i <= 5 { goto start } }
In the above code, the loop output1
to ## is realized through thegoto start
statement. #5effect. It should be noted that in Go language, the use of
gotostatements should be avoided as much as possible to avoid problems with code readability and maintainability.
The above is the detailed content of In-depth understanding of jump statements in Go language. For more information, please follow other related articles on the PHP Chinese website!