“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”
Write at the front π
Break, Continue, gotoπ§
1. Label π
Field declarations can be followed by an optional string literal (tag) called the property π₯ for all fields in the corresponding field declaration
- All three statements can be used with labels
- The label name is case sensitive (uppercase is recommended). If you do not use it later, a compilation error will occur
- The continue and break tags can be used to jump out of multiple loops
- Goto adjusts the execution position and is not the same as the result of the continue and break tags
Break statement π₯¨
In Go, break can terminate the for, swich, and slect blocks π₯―
- Grammar π
break
break label
Copy the code
- Sample π
package main
import "fmt"
func main(a) {
/* Tag marks the position of the outer loop */
OuterLoop:
for i := 0; i < 10; i++ {
fmt.Printf("π \ n")
for j := 0; j < 10; j++ {
fmt.Printf("π \ n")
if i == 1 && j == 1 {
/* Jump out of the OuterLoop code block */
break OuterLoop
}
}
}
fmt.Println("Break out of multiple cycles.")}Copy the code
- Results π
The continue statement π₯―
In Go, continue can only be used for, to skip the current loop once π₯
- Grammar π
continue
continue label
Copy the code
- Sample π
package main
import (
"fmt"
"time"
)
func main(a) {
j := 1
for i := 1; i <= 10; i++ {
time.Sleep(time.Second)
if i >= 5 && i <= 7 {
fmt.Printf("Pause %d seconds! \n", i4 -)
continue
} else {
fmt.Println(j)
j++
}
}
}
Copy the code
- Results π
Goto statement π§
In Go, the goto statement can unconditionally transfer the label position. Usually used in conjunction with conditional statements, can be used to achieve conditional transfer, form a loop, out of the loop body functions π₯
However, goTO statements are generally not recommended in structured programming, so as not to cause confusion in the program flow and make it difficult to understand and debug the program.
- Grammar π
goto label
Copy the code
- Sample π
package main
import (
"fmt"
"time"
)
func main(a) {
for i := 1; i <= 10; i++ {
time.Sleep(time.Second)
if i == 5 {
goto Out
}
fmt.Println(i)
}
Out:
fmt.Println("Count to five and I'll study!")}Copy the code
- Results π
Write it at the back π
Thank you for watching β¨. If you have any questions, please point them out to π