[GO Language Fundamentals] Basic skills that must be mastered for the three major processes of GO (4)

Process control

In the program, the flow control of the program operation determines how the program is executed, and we must master it. There are three main flow control statements.

  • Sequence control
  • Branch control
  • Loop control

Sequence control

The program is executed line by line from top to bottom, without any judgment or jump in the middle.

Branch control

There are three types of branch control for the selective execution of the program:

  • Single branch
    if 条件表达式 {
        //执行代码块
    }
  • Double branch
    if 条件表达式 {
        //执行代码块
    } else {
        //执行代码块
    }
  • Multi-branch
    if 条件表达式1 {
        //执行代码块 
    } else if 条件表达式2 {
        //执行代码块
    } else {
        //执行代码块
    }

    //在符合一个条件 执行相应代码块后 会结束
  1. {} is a must, even if you only write one line of code;
  2. Conditional expressions do not need parentheses
  3. The scope of the variable declared in the block is only in the block
  4. golang supports directly defining a variable in if
    if age := 20; age > 18 { 
        //代码块
    } 
  1. The conditional expression of the if statement cannot be an assignment statement
    if b = false { //错误

    } 
  1. The result of the conditional expression of the if statement must be a bool value
    n := 4 if n { //错误

    }

switch

The switch statement is used to perform different actions based on different conditions, and each case branch is unique, testing one by one from top to bottom until the matching position.

No need to add break after the match

Basic syntax:

    switch 表达式 {
        case 表达式1,表达式2, ... :
            语句块
        case 表达式3,表达式4, ... :
            语句块
        case 表达式5:
            语句块
        default:
            语句块
    }
  1. The execution flow of switch is to execute the expression first, get the value, and then compare it with the case expression. If it is equal, it matches, then execute the corresponding case statement block, and then exit the switch control. If none of them match , The default is executed.
  2. The default statement is not required.
  3. If the value of the switch expression does not match any case expression successfully, the default statement block is executed. Exit the switch control after execution.
  4. There can be multiple expressions after the case of golang, separated by commas.
  5. The case statement block in golang does not need to write break, because there is by default, that is, by default, when the program finishes executing the case statement block, it directly exits the switch control structure.
  6. fallthrough: The relationship with the following case condition is a logical OR, which is equivalent to adding a logical OR condition to the following case
  7. The data type of the value of each expression after the case must be consistent with the data type of the switch expression
package main

import "fmt"

func main() {

    var num1 int32 = 20
    var num2 int64 = 20

    switch num1 {

    case num2:
        fmt.Println("相等呢")
    case 30:
        fmt.Println("哈哈")

    }
}
//运行时报错
invalid case num2 in switch on num1 (mismatched types int64 and int32)

But if it’s a number, it’s okay, because the number itself doesn’t have a type.

package main

import "fmt"

func main() {

    var num1 int32 = 20

    switch num1 {

    case 20.0:
        fmt.Println("相等呢")
    case 30:
        fmt.Println("哈哈")

    }
}

  1. The expression after switch in golang is not even necessary
  2. Type switch
    switch statement can also be used in type-switch to determine the type of variable actually stored in an interface variable.
    The syntax format of Type Switch is as follows:
    switch x.(type) {
    case type:
        statement(s);
        case type:
        statement(s);
        //你可以定义任意个数的case
        default: /*可选*/
        statement(s);
    }

Example:

    package main

    import "fmt"

    func main() {

        var x interface{}

        switch i := x.(type) { //x.()格式是类型断言
        case nil:
            fmt.Printf("x 的类型是: %T", i)
        case int:
            fmt.Printf("x 的类型是: int")
        case float64:
            fmt.Printf("x的类型是: float64")
        case func(int) float64:
            fmt.Printf("x的类型是: func(int)")
        case bool, string:
            fmt.Printf("x的类型是: bool或string")
        default:
            fmt.Printf("未知型")
        }
    }
    //以上代码的执行结果为:
    x 的类型是: <nil>

  1. After the case is an expression (ie: constant value, variable, a function with a return value, etc.)
  2. If the expression behind the case is a constant value (literal), it must not be repeated
    package main

    import "fmt"

    func main() {

        var n1 int32 = 5
        var n2 int32 = 20
        var n3 int32 = 5
        switch n1 {

            case n2, 10, 5:
                fmt.Println("case1")
            case 5: //这里不允许重复出现数字5,但是如果我们把5替换成变量n3就不会报错
                fmt.Println("case2")
        }
    }

  1. You can also declare/define a variable directly after switch, ending with a semicolon, not recommended
    switch grade := 90; {
        case grade > 90:
        fmt.Println("成绩优秀...")
        case grade >= 60 && grade <= 90:
        fmt.Println("成就优良")
        default:
        fmt.Println("不及格")
    }

  1. Comparison of switch and if

If there are not many specific values ​​to be judged, and they conform to the types of integers, floating-point numbers, characters, and strings, it is recommended to use switch statements, which are concise and efficient.
Other situations: use if for interval judgments and judgments that the result is bool type, and if the scope of use is wider\

Loop control

The loop statement in Go language only supports the for keyword, and does not support the while and do-where structures.

for

Syntax:
There are three forms of for loop in Go language, and only one of them uses a semicolon.

  • Same as for for in C language:
    • init: Generally, it is an assignment expression, which assigns an initial value to the control variable;

    • condition: relational expression or logical expression; loop control condition

    • post: Generally an assignment expression, increment or decrement the control variable.

for init; condition; post {}

  • Same as C's while:
    • Write variable initialization and variable iteration to other locations
for condition {}

  • Same as C's for(;;):
    • If there is no break statement inside the for loop, it will loop forever, usually it needs to be used with the break statement
for {}

  • The range format of the for loop can iteratively loop over slices, maps, arrays, strings, etc. The format is as follows:

    • String traversal method 1-traditional method
        var str string = "hello, world"
        for i := 0; i < len(str); i++ {
            fmt.Printf("%c \n", str[i])
        }
    
    
    • String traversal method 2-for-range
        var str string = "hello, world"
        for key, value := range str {
            fmt.Printf("key=%d, value=%c \n", key, value)
        }
    
    

Question: If our string contains Chinese, then the traditional way of traversing the string is wrong, and garbled characters will appear. The reason is that the traditional traversal of strings is traversed in bytes, and a Chinese character corresponds to 3 bytes in utf8 encoding.
How to solve: It is necessary to convert str into []rune slices. Corresponding to the for-range traversal method, it is traversed in character. So if there are strings in Chinese, it is also possible

break

The break statement is used to terminate the execution of a statement block, to interrupt the current for loop or jump out of the switch statement. Break is to jump out of the entire loop.

When the break statement appears in a multi-level nested statement block, the label can be used to indicate which level of statement block is to be terminated.

    package main
    import "fmt"

    func main() {
        //label1:
        for i := 0; i < 4; i++ {
            label2:
            for j := 0; j < 5; j++ {
                if j == 2 {
                    //break  //break默认会跳出最近的循环
                    //break label1;
                    break label2;
                }
                fmt.Println("j = ", j)
            }
        }
    }

continue

The continue statement is used to end this loop and continue to execute the next loop.

When the continue statement appears in the body of a multi-level nested loop statement, the label can be used to know which level of loop to skip. This is the same as the previous break + label.

goto

  • Goto statements in Go language can unconditionally move to a specified line in the program.
  • The goto statement is usually used in conjunction with conditional statements. It can be used to realize conditional transitions, jump out of the loop and other functions.
  • In Go programming, the use of goto statements is generally not recommended , so as not to cause confusion in the program flow and make it difficult to understand and debug the program.
    grammar:
    goto label

    label: statement

Example:

    package main
    import "fmt"

    func main() {
        fmt.Println(1);
        goto label1
        fmt.Println(2);
        fmt.Println(3);
        fmt.Println(4);

        label1:
        fmt.Println(5);
    }
    //输出结果
    1
    5

return

return is used in a method or function to indicate the method or function where it exits

  1. If return is in an ordinary function, it means that the function is exited, that is, the code after return in the function is no longer executed, and it can also be understood as a termination function.
  2. If return is in the main function, it means that the main function is terminated, that is, the program is terminated.

defer

Before the function returns, the operation of the defer function is called to simplify the cleanup of the function.

  1. When the defer expression is determined, the parameters of the defer modified function (hereinafter collectively referred to as the deferred function) are also determined
  2. There can be multiple defered functions in a function, but these defered functions follow the last-in-first-out principle when the function returns
  3. The return value of the function name is used with the defered function

The return value of the function may be changed by defer. The essential reason is that the return xxx statement is not an atomic instruction. The execution process is: save the return value (if any) -> execute defer (if any) -> execute the return jump.

panic (equivalent to throwing an exception)

Panic is a built-in function that can stop the program execution flow.

  1. The caller function execution exits from the current call point
  2. The return value can be set through panic

The meaning of panic is not only to control the exception handling process, but also to return the cause of the exception.
If panic does not return the cause of the exception to the caller, then the caller will not be able to deal with the problem. Therefore, when panic is called, a string is generally returned to indicate the reason for the failure.
The return value of panic is obtained through the recover function.

  1. The defer operation before calling panic will be executed immediately after calling panic.

recover (equivalent to catching an exception)

The recover function is also a built-in function, specifically used to receive the return value of the panic function. When the panic function is not called or has no return value, recover returns Nil. The
capture function recover will only end with an error if it is called directly within the delayed call, otherwise it always returns nil. Any uncaught errors will be passed along the call stack.

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113934012