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
and goto
. 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 the switch
statement and terminate the subsequent code block. The following is an example of using the break
statement in a for
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 of i
is equal to 3, execute The break
statement breaks out of the loop, so only 1
and 2
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 the continue
statement in a for
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 of i
is equal to 3, execute The continue
statement skips the code in the current loop and directly enters the next cycle, so only 1
, 2
, 4
will be output. and 5
.
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 the goto
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 output 1
to ## is realized through the goto start
statement. #5 effect. It should be noted that in Go language, the use of
goto statements 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!