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 <p>output:</p><pre class="brush:php;toolbar:false">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 <p>output:</p><pre class="brush:php;toolbar:false">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!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


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 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment