Golang defer关键字

Golang defer关键字

在Go语言中,defer语句将函数或方法或匿名方法的执行defer到附近的函数返回。换句话说,defer函数或方法的调用参数会立即评估,但在附近的函数返回之前,它们不会执行。你可以通过使用 defer 关键字来创建一个defer的方法、或函数、或匿名函数。

语法

// Function
defer func func_name(parameter_list Type)return_type{
// Code
}

// Method
defer func (receiver Type) method_name(parameter_list){
// Code
}

defer func (parameter_list)(return_type){
// code
}()
Go

重要的一点

  • 在Go语言中,同一程序中允许有多个defer语句,它们以LIFO(Last-In, First-Out)顺序执行,如例2所示。
  • 在defer语句中,参数在defer语句执行时被评估,而不是在它被调用时被评估。
  • defer语句一般用于确保文件在其需要结束时被关闭,或关闭通道,或捕捉程序中的恐慌。

让我们借助于一个例子来讨论这个概念。

例1 :

// Go program to illustrate the
// concept of the defer statement
package main
 
import "fmt"
 
// Functions
func mul(a1, a2 int) int {
 
    res := a1 * a2
    fmt.Println("Result: ", res)
    return 0
}
 
func show() {
    fmt.Println("Hello!, GeeksforGeeks")
}
 
// Main function
func main() {
 
    // Calling mul() function
    // Here mul function behaves
    // like a normal function
    mul(23, 45)
 
    // Calling mul()function
    // Using defer keyword
    // Here the mul() function
    // is defer function
    defer mul(23, 56)
 
    // Calling show() function
    show()
}
Go

输出

Result:  1035
Hello!, GeeksforGeeks
Result:  1288
Go

解释: 在上述例子中,我们有两个名为mul()和show()的函数。show()函数在main()函数中被正常调用,而mul() 函数则以两种不同方式被调用。

  • 首先,我们正常调用mul函数(没有defer关键字),即mul(23, 45),当函数被调用时它会执行(输出:结果:1035)。
  • 第二,我们使用defer关键字将mul()函数作为defer函数调用,即defer mul(23, 56) ,当周围的方法都返回时,它就会执行(输出:结果:1288)。

例2 :

// Go program to illustrate
// multiple defer statements, to illustrate LIFO policy
package main
 
import "fmt"
 
// Functions
func add(a1, a2 int) int {
    res := a1 + a2
    fmt.Println("Result: ", res)
    return 0
}
 
// Main function
func main() {
 
    fmt.Println("Start")
 
    // Multiple defer statements
    // Executes in LIFO order
    defer fmt.Println("End")
    defer add(34, 56)
    defer add(10, 10)
}
Go

输出

Start
Result:  20
Result:  90
End
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册