What is the usage of defer in go language?
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.
#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 }
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 }
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) } }
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") }
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
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") }
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

Regarding the problem of custom structure tags in Goland When using Goland for Go language development, you often encounter some configuration problems. One of them is...

The correct way to implement efficient key-value pair storage in Go language How to achieve the best performance when developing key-value pair memory similar to Redis in Go language...

Performance optimization strategy for Go language massive URL access This article proposes a performance optimization solution for the problem of using Go language to process massive URL access. Existing programs from CSV...
