1. Conditional statements
1.1 if statement
The if statement is a commonly used conditional statement that is used to execute a specific code block based on a certain condition. In Golang, the syntax of an if statement is as follows:
if condition { // Execute code block } else if condition2 { // Execute code block 2 } else { // Execute code block 3 }
Where, condition is a condition that needs to be judged. If its value is true, execute the code block after the if statement; if the value of condition is false, execute the code block after the else statement. If there is an else if statement after the if statement, the conditions of each else if statement will be judged in turn. If the condition is true, the corresponding code block will be executed, otherwise the conditions of the next else if statement will continue to be judged. If all else if statements do not meet the conditions, execute the code block after the else statement.
Here is a simple if statement example:
package main import "fmt" func main() { age := 20 if age >= 18 { ("Adults") } else { ("Minor") } }
The output result is:
Adults
1.2 switch statement
The switch statement is also a commonly used conditional statement, which is used to select the executed code block in multiple different branches according to the value of the variable. In Golang, the syntax of a switch statement is as follows:
switch variable { case value1: // Execute code block 1 case value2: // Execute code block 2 default: // Execute the default code block }
Among them, variable is a variable that needs to be judged, and case is a condition for value matching. If the value of variable is equal to the value in case, the corresponding code block is executed; if no case matches the value of variable, the code block after the default statement is executed.
Here is a simple switch statement example:
package main import "fmt" func main() { fruit := "apple" switch fruit { case "banana": ("This is a banana") case "apple": ("This is Apple") default: ("This is other fruit") } }
The output result is:
This is Apple
2. Loop statements
2.1 for statement
The for statement is a commonly used loop statement that is used to repeatedly execute a certain code block, and can also be used to iterate elements in data structures such as arrays, slices, and maps. In Golang, the syntax of a for statement is as follows:
for initialization; condition; increment { // Execute code block }
Among them, initialization is an initialization statement, which can be used to initialize the loop counter; condition is a loop condition. If the value of condition is true, the code block after the for statement is executed; increment is an update statement of the loop counter. After each loop is executed, an increment statement will be executed to update the value of the loop counter.
Here is a simple example for statement to calculate sums from 1 to 10:
package main import "fmt" func main() { sum := 0 for i := 1; i <= 10; i++ { sum += i } ("The sum of 1 to 10 is:", sum) }
The output result is:
The sum of 1 to 10 is: 55
2.2 range statement
The range statement is used to iterate over elements in data structures such as arrays, slices, and maps. In Golang, the syntax of a range statement is as follows:
for index, value := range array/slice/map { // Execute code block}
where index is the subscript or key of the element, and value is the value of the element. When iterating over an array or slice, index represents the subscript of the element; when iterating over a map, index represents the key of the element. Here is a simple range statement example used to iterate over an array:
package main import "fmt" func main() { numbers := [5]int{1, 2, 3, 4, 5} for i, num := range numbers { ("Subscript as", i, "The element is:", num) } }
The output result is:
The elements with a subscript of 0 are: 1
The elements with subscript 1 are: 2
The elements with subscript 2 are: 3
The elements with subscript 3 are: 4
The elements with subscript 4 are: 5
3. Jump statement
3.1 break statement
The break statement is used to break out of the current loop statement. In Golang, the syntax of a break statement is as follows:
for initialization; condition; increment { // Execute code block if condition2 { break } }
Where, if the value of condition2 is true, the break statement is executed to break out of the loop.
Here is a simple break statement example to find the first negative number in the array:
package main import "fmt" func main() { numbers := [5]int{1, 2, -3, 4, 5} for _, num := range numbers { if num < 0 { ("Finish the first negative number:", num) break } } }
The output result is:
Find the first negative number: -3
3.2 continue statement
The continue statement is used to skip a certain iteration in the current loop and directly enter the next iteration. In Golang, the syntax of a continue statement is as follows:
for initialization; condition; increment { // Execute code block if condition2 { continue } }
Where, if the value of condition2 is true, execute the continue statement, skip the current iteration, and directly enter the next iteration.
Here is a simple example of a continue statement to print odd numbers between 1 and 10:
package main import "fmt" func main() { for i := 1; i <= 10; i++ { if i%2 == 0 { continue } (i) } }
The output result is:
1
3
5
7
9
3.3 goto statement
The goto statement is used to unconditionally jump to the specified tag. In Golang, the syntax of a goto statement is as follows:
goto label ... label: // Execute code blocks
Where label is an identifier used to mark a certain code block. When executing the goto statement, it will jump to the specified tag and continue to execute the subsequent code block.
Here is a simple goto statement example to simulate a dead loop:
package main func main() { Loop: for { goto Loop } }
In the example above, the program will keep executing the for loop without stopping.
4. Error handling statements
In Golang, error handling is a very important task because it can help programs handle errors better, thereby improving program reliability and stability.
4.1 defer statement
The defer statement is used to perform certain operations before the function exits, such as closing files, freeing resources, etc. In Golang, the syntax of the defer statement is as follows:
defer func_name(args)
Where func_name is the function name to be executed, and args is the function parameter list. When the function exits, all defer statements are executed in turn.
Here is a simple defer statement example to demonstrate the execution order of the defer statement:
package main import "fmt" func main() { defer ("defer 1") defer ("defer 2") defer ("defer 3") ("Hello, world!") }
The output result is:
Hello, world! defer 3 defer 2 defer 1
In the example above, execute the ("Hello, world!") statement first, and then execute all the defer statements in turn.
4.2 panic statement
The panic statement is used to raise a runtime error and crash the program. In Golang, the syntax of a panic statement is as follows:
panic("error message")
Where "error message" is a string that describes the error message. When the program executes a panic statement, a panic error is raised and the program crashes.
4.3 recover statement
The recover statement is used to restore the execution of the program. If a panic error occurs in the program, the recover statement can be used to catch the error and handle it accordingly. In Golang, the syntax of the recover statement is as follows:
The recover statement is used to restore the execution of the program. If a panic error occurs in the program, the recover statement can be used to catch the error and handle it accordingly. In Golang, the syntax of the recover statement is as follows:
package main import "fmt" func main() { defer func() { if err := recover(); err != nil { ("recover error:", err) } }() panic("panic error") }
The output result is:
recover error: panic error
In the example above, the defer statement is used to define an anonymous function to catch panic errors and output error messages.
5. Summary
Process control statements are a very important part of programming. They can help us control the execution process of programs and implement complex logical functions. In Golang, process control statements include two types: branch control statements and loop control statements, which are used to control the branches and loops of the program.
When learning process control statements, we need to understand the grammar and usage of each statement, as well as the differences and connections between them. At the same time, we also need to pay attention to some precautions, for example, when using an if statement, we need to pay attention to the priority relationship of multiple conditions; when using a switch statement, we need to pay attention to the break keyword of the case statement; when using a loop control statement, we need to pay attention to the execution order and termination conditions of the loop.
Finally, it should be emphasized that although process control statements are very useful, in actual programming, we also need to pay attention to the readability and maintainability of the code, and try to avoid too many nesting and complex control processes, so that the code is more concise and easy to understand.
The above is the detailed content of in-depth study of Golang's process control. For more information about Golang's process control, please follow my other related articles!