What is the usage of defer in go language?

王林
Release: 2023-01-11 09:23:20
Original
4759 people have browsed it

Usage of defer in go language: 1. The defer statement is executed before the function returns or after the return statement in the function; 2. The execution order of multiple defer statements is in reverse order; 3. The defer after the panic statement The statement is not executed.

What is the usage of defer in go language?

#The operating environment of this article: windows10 system, GO 1.11.2, thinkpad t480 computer.

(Learning video sharing: Programming video)

Usage introduction:

defer is a delayed execution statement in the Go language, used to add the end of a function Code that is executed when executing, often used to release certain allocated resources, close database connections, disconnect socket connections, and unlock a locked resource. The Go language mechanism guarantees that the code in the defer statement will be executed.

There are similar mechanisms in other languages, such as the finally statement in Java and C#, and the destructor in C language can play a similar role. The C language mechanism guarantees that the object must be destroyed before it is destroyed. The code in the destructor will be executed. The destructor in C destructs the object, and the defer in Go destructs the function.

1. Execution timing of defer statement

The defer statement is executed before the function returns or after the return statement in the function (the return statement may call another function). Sample code:

package main
 
import (
    "fmt"
)
 
func main() {
    fmt.Println(deferReturn())
}
 
func deferReturn() (ret int) {
    defer func() {
        ret++
    }()
    return 10
}
Copy after login

The value printed by the above code is: 11. The "ret" in the defer statement in the anonymous function adds 1 to the return value 10 to become 11. Let’s look at the code where a defer statement appears after the return statement:

func returnDefer() (ret int) {
    return 0
    defer func() {
        ret++
        ret++
    }()
    return 1
}
Copy after login

The return value of the above returnDefer function is: 0. The reason is that the defer statement returns before adding code and executing the "return 0" function, so the defer statement is not executed.

2. The execution order of multiple defer statements is reverse order

When multiple defer statements appear, they are executed in reverse order (similar to a stack, that is, last in, first out). Sample code:

func deferSample() {
    for i := 0; i < 5; i++ {
        defer fmt.Printf("%d ", i)
    }
}
Copy after login

The above code will output: 4 3 2 1 0

3. Defer and panic

1. The defer statement after the panic statement will not be executed.

Sample code:

func panicDefer() {
    panic("panic")
    defer fmt.Println("defer after panic")
}
Copy after login

The output of the above code is as follows:

panic: panic
goroutine 1 [running]:
main.panicDefer()
    E:/godemo/testdefer.go:17 +0x39
main.main()
    E:/godemo/testdefer.go:13 +0x20
Process finished with exit code 2
Copy after login

You can see that the defer statement is not executed.

2. The defer statement before the panic statement will be executed

Sample code:

func deferPanic() {
    defer fmt.Println("defer before panic")
    panic("panic")
}
Copy after login

The output of the above code is as follows:

defer before panic
panic: panic
goroutine 1 [running]:
main.deferPanic()
    E:/godemo/testdefer.go:19 +0x95
main.main()
    E:/godemo/testdefer.go:14 +0x20
Process finished with exit code 2
Copy after login

defer statement output content.

Panic in Go is similar to throwing exceptions in other languages. The code after panic will no longer be executed (the defer statement before the panic statement will be executed).

4. The implementation logic of return

1. The first step is to assign a value to the return value (if the named return value is assigned directly, the anonymous return value is declared first and then assigned);
2. In the second step, call the RET return instruction and pass in the return value. RET will check whether there is a defer statement. If it exists, it will first insert the defer statement in reverse order;
3. Finally, RET will exit the function with the return value.

It can be seen that return is not an atomic operation, and the function return value is not necessarily consistent with the RET return value.

5. The order of defer, return, and return value

The execution order of defer, return, and return value is: return first assigns a value to the return value; then defer begins to execute some finishing touches Work; finally the RET instruction exits the function with the return value.

Related recommendations: golang tutorial

The above is the detailed content of What is the usage of defer in go language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!