What is defer in Go? how to use?
This article is introduced to you by the go language tutorial column. The topic is about the learning and use of go defer. I hope it will be helpful to friends in need!
What is defer?
In Go, a function call can follow a defer
keyword to form a deferred function call.
When a function call is delayed, it will not be executed immediately. It will be pushed into a deferred call stack maintained by the current coroutine. When a function call (which may or may not be a deferred call) returns and enters its exit phase, all deferred calls that have been pushed within this function call will be executed in reverse order of the order in which they were pushed onto the stack. When all these delayed calls are executed, the function call actually exits.
A simple example:
package mainimport "fmt"func sum(a, b int) { defer fmt.Println("sum函数即将返回") defer fmt.Println("sum函数finished") fmt.Printf("参数a=%v,参数b=%v,两数之和为%v\n", a, b, a+b)}func main() { sum(1, 2)}
output:
参数a=1,参数b=2,两数之和为3 sum函数finished sum函数即将返回
In fact, each coroutine maintains two call stacks.
- One is a normal function call stack. In this stack, two adjacent calls have a calling relationship. Calls that are placed on the stack late are called by calls that are placed on the stack early. The earliest call pushed in this stack is the start call of the corresponding coroutine.
- The other stack is the delayed call stack mentioned above. There is no call relationship between any two calls in the deferred call stack.
defer function parameter valuation
- For a delayed function call, its actual parameters are the values that are called when this function is called. Evaluated when pushed into the deferred call stack.
- The expressions in an anonymous function body will be evaluated one by one when the function is executed, regardless of whether the function is called normally or delayed.
Example 1:
package mainimport "fmt"func Print(a int) {fmt.Println("defer函数中a的值=", a)}func main() {a := 10defer Print(a)a = 1000fmt.Println("a的值=", a)}
output:
a的值= 1000 defer函数中a的值= 10
defer Print(a) When it is added to the delayed call stack, the value of a is 5, so defer Print(a ) The output result is 5
Example 2:
package mainimport "fmt"func main() { func() { for i := 0; i < 3; i++ { defer fmt.Println("a=", i) } }() fmt.Println() func() { for i := 0; i < 3; i++ { defer func() { fmt.Println("b=", i) }() } }()}
output:
a= 2 a= 1 a= 0 b= 3 b= 3 b= 3
i in the first anonymous function loop is pushed into the delayed call stack during the fmt.Println function call The value estimated when , so the output result is 2, 1, 0. i in the second anonymous function is the value estimated during the exit phase of the anonymous function call (i has become 3 at this time), so the output result is: 3, 3,3.
In fact, by slightly modifying the second anonymous function call, you can make it output the same result as the anonymous function one:
package mainimport "fmt"func main() { func() { for i := 0; i < 3; i++ { defer fmt.Println("a=", i) } }() fmt.Println() func() { for i := 0; i < 3; i++ { defer func(i int) { fmt.Println("b=", i) }(i) } }()}
output:
a= 2 a= 1 a= 0 b= 2 b= 1 b= 0
Panic and recovery(defer recover)
Go does not support exception throwing and catching, but it is recommended to use return values to explicitly return errors. However, Go supports a similar mechanism to exception throwing/catching. This mechanism is called the panic/recover mechanism.
We can call the built-in function panic
to generate a panic so that the current coroutine enters a panic state.
Entering a panic condition is another way to cause the current function call to start returning. Once a function call generates a panic, the function call will immediately enter its exit phase, and the deferred calls pushed onto the stack within the function call will be executed in reverse order of the order in which they were pushed.
By calling the built-in function recover
within a delayed function call, a panic in the current coroutine can be eliminated, allowing the current coroutine to re-enter normal conditions.
Before a coroutine in panic exits, the panic will not spread to other coroutines. If a coroutine exits in a panic condition, it will crash the entire program. Look at the following two examples:
package mainimport ( "fmt" "time")func p(a, b int) int { return a / b}func main() { go func() { fmt.Println(p(1, 0)) }() time.Sleep(time.Second) fmt.Println("程序正常退出~~~")}
output:
panic: runtime error: integer pide by zero goroutine 6 [running]: main.p(...) /Users/didi/Desktop/golang/defer.go:9 main.main.func1() /Users/didi/Desktop/golang/defer.go:14 +0x12 created by main.main /Users/didi/Desktop/golang/defer.go:13 +0x39exit status 2
p function panics (divisor is 0), because the coroutine does not have a panic recovery mechanism, causing the entire program to crash.
If the coroutine where the p function is located is added with panic recovery (defer recover), the program can exit normally.
package mainimport ( "fmt" "time")func p(a, b int) int { return a / b}func main() { go func() { defer func() { v := recover() if v != nil { fmt.Println("恐慌被恢复了:", v) } }() fmt.Println(p(1, 0)) }() time.Sleep(time.Second) fmt.Println("程序正常退出~~~")}
output:
恐慌被恢复了: runtime error: integer pide by zero 程序正常退出~~~
For more golang related knowledge, please visit the golangtutorial column! ##
The above is the detailed content of What is defer in Go? how to use?. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
