Go语言现代web开发defer 延迟执行
The defer statement will delay the execution of a function until the surrounding function is completed. Although execution is postponed, funciton arguments will be evaluated immediately.
defer语句将延迟函数的执行,直到周围的函数完成。虽然执行被延迟,但函数参数将立即求值。
Defer is quite useful in situations when we should execute a specific function call after the execution of the surrounding function. It is often used to close files, streams, or connections to a database because defer will be executed even if the function fails; so, we do not need to handle all situations when something goes wrong, one simple defer statement will take care of it.
当我们应该在执行周围函数之后执行特定的函数调用时,Defer非常有用。它通常用于关闭文件、流或与数据库的连接,因为即使函数失败,也会执行defer;因此,当出现问题时,我们不需要处理所有情况,一个简单的defer语句就可以处理它。
In the following example, the execution of fmt.Print(2) will be postponed until main() function is concluded;
在下面的例子中,fmt.Print(2)的执行将被延迟,直到main()函数结束;
func main(){
fmt.Print(1)
defer fmt.Print(2)
fmt.Print(3)
}
Value 132 will be displayed on the standard output.
标准输出将显示132。
We can have more than one defer statement inside a function. The function call will be pushed onto a stack. The stack can be defined as a collection of elements, where the most recently added element will be removed first. This principle is called LIFO, Last, first out.
在一个函数中可以有多个defer语句。函数调用将被压入堆栈。堆栈可以定义为元素的集合,其中最近添加的元素将首先被删除。这个原则被称为后进先出。
The following code snippet will print 1342 on standard output. The first print will be executed, be second one (under defer) will be pushed onto the stack the third print will be executed, and the fourth one will be pushed onto the stack. Deferred function calls on the stack are presented in next. Since the fourth print is pushed onto the stack last, it will be executed first.
下面的代码片段将在标准输出中打印1342。第一次打印将被执行,第二次打印(在defer下)将被压入堆栈,第三次打印将被执行,第四次打印将被压入堆栈。堆栈上的延迟函数调用在next中给出。由于第四次打印最后被压入堆栈,因此它将首先执行。
func main(){
fmt.Print(1)
defer fmt.Print(2)
fmt.Print(3)
defer fmt.Print(4)
}
If defer is declared after return, the function call will not be executed, because defer statement will not be executed, and the function call will not be pushed into the stack. In the following example, first call of the testDefer() function will execute will four calls of the Print() function, and the second call will not execute the fourth one.
如果在return之后声明了defer,函数调用将不会被执行,因为defer语句不会被执行,函数调用也不会被压入堆栈。在下面的示例中,testDefer()函数的第一次调用将执行对Print()函数的四次调用,而第二次调用将不执行第四次调用。
func testDefer(val int){
fmt.Print(1)
defer fmt.Print(2)
fmt.Print(3)
if val == 5{
return
}
defer fmt.Print(4)
}
func main(){
testDefer(3)
testDefer(5)
}
Value 1342132 will be displayed on the standard output.
标准输出将显示1342132的值。