There are so many process control methods in Go:
-
if - else conditional statement
-
switch - case selection statement
-
for - range loop statement
-
goto unconditional jump statement
-
Defer defer execution
if-else conditional statement
if condition 1 { Branch 1 } else if condition 2 { Branch 2 } else if condition... { Branch... } else { Branch else }
The Go compiler strictly requires else if (or else) and curly braces (both {and}) to be on the same line.
Because Go s are strongly typed, conditional expressions must strictly return Boolean data (neither nil, 0, nor 1).
Single Branch Judgment
Only one if, no else
import "fmt" func main() { age := 20 if age > 18 { fmt.Println("Adult") } }
If more than one condition needs to be met within a condition, you can use && and ||
-
&&: Indicates that both sides need to be true for the final result to be true, otherwise false
-
||: Indicates or, if only one of the left and right is true, the final result is true, otherwise false
import "fmt" func main() { age := 20 gender := "male" if (age > 18 && gender == "male") { fmt.Println("Is an adult male") } }
Multi-Branch Judgment
if - else statement
import "fmt" func main() { age := 20 if age > 18 { fmt.Println("Adult") } else { fmt.Println("Not yet Adult") } }
if - else if - else statement
import "fmt" func main() { age := 20 if age > 18 { fmt.Println("Adult") } else if age >12 { fmt.Println("Already a teenager") } else { fmt.Println("Not a teenager yet") } }
Advanced Writing
In if, you can allow an expression to be run, get a variable, and then judge it, for example:
import "fmt" func main() { if age := 20;age > 18 { fmt.Println("Adult") } }
switch-case selection statement
switch expression { case expression 1: Code Block case expression 2: Code Block case expression 3: Code Block case expression 4: Code Block case expression 5: Code Block default: Code Block }
Contrast the expression after switching with that after case. As long as one case meets the criteria, the corresponding code block is executed, and switch-case exits directly. If none of them is satisfied, the default code block is executed.
Example
The switch is followed by a variable you want to judge, education, and then case will use it to judge the expression behind it (which may be a constant, a variable, an expression, etc.).
If equal, the corresponding code block is executed.If not, proceed to the next case.
import "fmt" func main() { education := "Undergraduate" switch education { case "doctor": fmt.Println("I am a doctor") case "Graduate student": fmt.Println("I am a postgraduate") case "Undergraduate": fmt.Println("i am an undergraduate") case "Junior College": fmt.Println("I'm a junior college student") case "high school": fmt.Println("I am a high school student") default: fmt.Println("Educational qualifications do not meet the standards..") } } //The output is as follows: //i am an undergraduate
Multiple conditions for a case
After a case, multiple conditions can be followed, with a comma-separated relationship between or (||).
import "fmt" func main() { month := 2 switch month { case 3, 4, 5: fmt.Println("spring") case 6, 7, 8: fmt.Println("summer") case 9, 10, 11: fmt.Println("Autumn") case 12, 1, 2: fmt.Println("winter") default: fmt.Println("Input Error...") } } //The output is as follows: //winter
case condition constant cannot be repeated
When a case is followed by a constant, it can only appear once
There are two cases where errors will occur at compile time: duplicate case "male" in switch
Error Example 1:
gender := "male" switch gender { case "male": fmt.Println("Male") //Repeat with above case "male": fmt.Println("Male") case "female": fmt.Println("Female sex") }
Error Example 2:
gender := "male" switch gender { case "male", "male": fmt.Println("Male") case "female": fmt.Println("Female sex") }
switch succeeding function
A switch can be followed by a function provided that the value type after the case is the same as the return value of the function.
import "fmt" //Function to determine if a student has a record of a registered subject //The return value is of Boolean type func getResult(args ...int) bool { for _, i := range args { if i < 60 { return false } } return true } func main() { chinese := 80 english := 50 math := 100 switch getResult(chinese, english, math) { //case must be followed by Boolean type case true: fmt.Println("The student passed all grades") case false: fmt.Println("The student has a record of registered subjects") } }
switch disjoint expression
After switching, no variables, expressions, functions can be connected. In this case, switch - case is equivalent to if - else if - else
score := 30 switch { case score >= 95 && score <= 100: fmt.Println("excellent") case score >= 80: fmt.Println("good") case score >= 60: fmt.Println("qualified") case score >= 0: fmt.Println("Unqualified") default: fmt.Println("Input Error...") }
The penetration ability of switch
The normal order in which switch-case executes is to exit switch-case directly as long as one case meets the criteria, and execute the default block of code if none of them is satisfied.
Exception: When case uses the keyword fallthrough to turn on penetration.
s : = "hello" switch { case s == "hello": fmt.Println("hello") fallthrough case s != "world": fmt.Println("world") } //The output is as follows: hello world
It is important to note that fallthrough can only penetrate one layer, meaning that it only gives one chance to re-evaluate a case, whether there is a match or not, and it will exit after execution:
s := "hello" switch { case s == "hello": fmt.Println("hello") fallthrough case s != "xxxx": fmt.Println("xxxx") case s != "world": fmt.Println("world") } //The output is as follows, and the world is not output (even if it meets the criteria): hello xxxx
for Loop Statement
for loop format:
for [condition | ( init; condition; increment ) | Range | Disjoint expression] { statement(s); }
After for, you can have three types of expressions:
-
Next conditional expression
-
Next to three expressions
-
Next range expression
-
Disjoint expression
Next conditional expression
This example prints values from 1 to 5.
import "fmt" func main() { a := 1 for a <= 5 { fmt.Println(a) a ++ } } //The output is as follows: 1 2 3 4 5
Next to three expressions
for followed by three expressions, use; delimit:
-
First expression: Initialize the control variable and run it only once throughout the life cycle;
-
The second expression: sets the loop control condition, returns true, continues the loop, returns false, and ends the loop;
-
Third expression: increment or decrement of the control variable each time the loop starts (except for the first time).
The examples on this side are equivalent to those above.
import "fmt" func main() { for i := 1; i <= 5; i++ { fmt.Println(i) } } //The output is as follows: 1 2 3 4 5
Contiguous expression: infinite loop
In the Go language, there are no while loops and an infinite loop is implemented using for.
When you do not add any criteria, it is equivalent to your true judgment every time, the program will always be running, but generally we will not let the program in a dead loop, under certain conditions, you can use the keyword break to exit the loop, or continue to jump directly to the next cycle.
Both of the following are written in an infinite loop.
for { Code Block } // Equivalent to for ;; { Code Block }
Lift a chestnut:
import "fmt" func main() { var i int = 1 for { if i > 5 { break } fmt.Printf("hello, %d\n", i) i++ } } //The output is as follows: hello, 1 hello, 2 hello, 3 hello, 4 hello, 5
Follow the for-range statement
Go s can use for-range to traverse an iterative object.Range can be connected to arrays, slices, strings, etc.
Since range returns two values: index and data, the unused return values are represented by an underscore:
import "fmt" func main() { myarr := [...]string{"world", "python", "go"} for _, item := range myarr { fmt.Printf("hello, %s\n", item) } } //The output is as follows: hello, world hello, python hello, go
goto
goto means jump.
goto is followed by a label of where the code will be executed next, modeled as follows:
goto tag; ... ... Label: expression;
Example
goto can break the original code execution order and jump directly to a line to execute the code:
import "fmt" func main() { goto flag fmt.Println("B") flag: fmt.Println("A") } The output is as follows: Execution results, not B, but A
How to use
A goto statement is usually used in conjunction with a conditional statement.Can be used to achieve conditions transfer, form a cycle, jump out of the cycle body and other functions.
Hold a chestnut and use goto to achieve a cycle of 1 to 5 prints.
import "fmt" func main() { i := 1 flag: if i <= 5 { fmt.Println(i) i++ goto flag } } //The output is as follows: 1 2 3 4 5
Lift a chestnut and use goto to achieve the effect of type break.
import "fmt" func main() { i := 1 for { if i > 5 { goto flag } fmt.Println(i) i++ } flag: }
The output is as follows
1 2 3 4 5
Raise another chestnut, use goto to achieve the effect of type continue, print all even numbers from 1 to 10.
import "fmt" func main() { i := 1 flag: for i <= 10 { if i%2 == 1 { i++ goto flag } fmt.Println(i) i++ } }
The output is as follows
2 4 6 8 10
Matters needing attention
A variable declaration cannot exist between a goto statement and a label, otherwise a compilation error occurs.
import "fmt" func main() { fmt.Println("start") goto flag var say = "hello oldboy" fmt.Println(say) flag: fmt.Println("end") }
Compilation error
.\main.go:7:7: goto flag jumps over declaration of say at .\main.go:8:6