summary
Process control is mainly used to set the order of calculation and execution and establish the logical structure of the program. The process control of Go language is similar to that of other programming languages, and supports the following process control statements:
- Conditional statement: used for conditional judgment. The corresponding keywords are {if, else} and {else if;
- Branch statement: used for branch selection. The corresponding keywords are "switch", "case" and "select" (used for channels, which will be mentioned later in the description of collaboration);
- Circular statement: used for circular iteration. The corresponding keywords are , for , and , range;
- Jump statement: used for code jump. The corresponding keywords are {goto.
1, Conditional statement
Example templates for conditional statements are as follows:
// if if condition { // do something } // if...else... if condition { // do something } else { // do something } // if...else if...else... if condition1 { // do something } else if condition2 { // do something else } else { // catch-all or default }
A simple conditional statement example code is as follows:
score := 100 if score > 90 { fmt.Println("Grade: A") } else if score > 80 { fmt.Println("Grade: B") } else if score > 70 { fmt.Println("Grade: C") } else if score > 60 { fmt.Println("Grade: D") } else { fmt.Println("Grade: F") }
matters needing attention
For conditional statements in Go language, you should pay attention to the following points:
- Conditional statements do not need to contain conditions with parentheses ();
- No matter how many statements there are in the statement body, curly braces {} must exist;
- The left curly bracket {must be on the same line as if or else;
- After , and before the conditional statement, you can add a variable initialization statement and use; Interval, for example, the above code can be written as follows: = if score = 100; score > 90 {
2, Branch statement
Branch statements will select different branch codes for execution according to different incoming conditions.
The branch statements of Go language are similar to those of other programming languages, except that you do not need to explicitly exit through the "break" statement in each branch structure:
switch var1 { case val1: ... case val2: ... default: ... }
Overwrite with branch statement i Example code of f statement:
score := 100 switch { case score >= 90: fmt.Println("Grade: A") case score >= 80 && score < 90: fmt.Println("Grade: B") case score >= 70 && score < 80: fmt.Println("Grade: C") case score >= 60 && score < 70: fmt.Println("Grade: D") default: fmt.Println("Grade: F") }
Note that at this time, the variable # score # cannot be placed after the # switch # keyword, otherwise an error will be reported. This can only be done when judging with the # case # branch value:
score := 100 switch score { case 90, 100: fmt.Println("Grade: A") case 80: fmt.Println("Grade: B") case 70: fmt.Println("Grade: C") case 60: case 65: fmt.Println("Grade: D") default: fmt.Println("Grade: F") }
Merge branch
In Go language, we can separate different branch conditions with commas to achieve the purpose of merging branch statements, such as "case 90100", instead of merging the same branch statements through multiple adjacent "case" statements like other languages
func testSwitch() { switch n := 7; n { case 1, 3, 5, 7, 9: fmt.Println("Odd number") case 2, 4, 6, 8: fmt.Println("even numbers") default: fmt.Println(n) } }
Branches can also use expressions. In this case, the switch statement does not need to be followed by a judgment variable
func switchDemo4() { age := 30 switch { case age < 25: fmt.Println("Study hard") case age > 25 && age < 35: fmt.Println("Work hard") case age > 60: fmt.Println("Enjoy it") default: fmt.Println("It's good to be alive") } }
fallthrough
fallthrough syntax can execute the next case of a case that meets the conditions, which is designed to be compatible with the case in C language.
func switchDemo5() { s := "a" switch { case s == "a": fmt.Println("a") fallthrough case s == "b": fmt.Println("b") case s == "c": fmt.Println("c") default: fmt.Println("...") } }
Output:
a
b
matters needing attention
Using switch in Go language case... When branching statements, you should pay attention to the following points:
- As with conditional statements, the left curly bracket {must be on the same line as "switch";
- Multiple result options (separated by commas) can appear in a single case;
- Different from other languages, Go language does not need to use "break" to explicitly exit a "case";
- Only when the "fallthrough" keyword is explicitly added to the "case", the next "case" will continue to be executed;
- The conditional expression after {switch} can not be set. In this case, the whole switch structure is connected with multiple} if else... The logical function of is equal.
3, Circular statement
for loop
Loop statements in Go language only support the for keyword, not the while and do while structures. The basic usage of the keyword ^ for ^ is similar to that of other languages, except that the loop condition does not contain parentheses. For example, if we want to calculate the sum of all numbers between 1 and 100, we can do this:
//for initial statement; Conditional expression; End statement{ // Loop body statement //}
sum := 0 for i := 1; i <= 100; i++ { sum += i } fmt.Println(sum)
Infinite loop
Go language does not support , while , and , do while , loop statements. For infinite loop scenarios, you can use , for , statements without loop conditions. Next, we rewrite the above calculation of the sum of numbers within 1 to 100 through infinite loop. The implementation is as follows:
//for { // Loop body statement //}
// The for loop can be forced to exit the loop through break, goto, return and panic statements.
sum := 0 i := 0 for { i++ if i > 100 { break } sum += i } fmt.Println(sum)
For range structure
The Go language also supports loop traversal through the {for range} structure. The following is an example
Traversal slice a := []int{1, 2, 3, 4, 5, 6} for k, v := range a { fmt.Println(k, v) } Ignore index/key for _, v := range a { fmt.Println(v) } Ignore element values for k := range a { fmt.Println(k) }
Cycle based on conditional judgment
Loop based on condition judgment. The code in the loop body will be executed only if the specified conditions are met
sum := 0 i := 0 for i < 100 { i++ sum += i } fmt.Println(sum)
goto
Goto statement performs unconditional jump between codes through tags. Goto statement can help to jump out of the loop quickly and avoid repeated exit. Using goto statement in Go language can simplify the implementation process of some codes. For example, when a double nested for loop is about to exit:
func gotoDemo1() { var breakFlag bool for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { // Set exit label breakFlag = true break } fmt.Printf("%v-%v\n", i, j) } // Outer loop judgment if breakFlag { break } } }
Using goto statement can simplify the code:
func gotoDemo2() { for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if j == 2 { // Set exit label goto breakTag } fmt.Printf("%v-%v\n", i, j) } } return // label breakTag: fmt.Println("end for loop") }
4, Precautions
When using circular statements in Go language, you should pay attention to the following points:
- Like conditional statements and branch statements, the left curly bracket {must be on the same line as "for";
- Circular statements with , while , and , do while , structures are not supported;
- Iteratable sets can be traversed through the {for range} structure;
- Support cyclic iteration based on conditional judgment;
- Variables can be defined and initialized in loop conditions, and multiple assignments are supported;
- The for loop of Go language also supports continue and break to control the loop, but it provides a more advanced break loop, which can be interrupted, as shown in the following example:
JLoop: for j := 0; j < 5; j++ { for i := 0; i < 10; i++ { if i > 5 { break JLoop } fmt.Println(i) } }