English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang function & method

Golang struct

Golang slice & array

Golang string(String)

Golang pointer

Golang interface

Golang concurrency

Golang exception(Error)

Golang other items

Go Defer Keyword

In Go language, the defer statement will delay函数or method orAnonymous methoduntil the nearby function returns. In other words, the evaluation of the deferred function or method call is immediate, but they will execute until the nearby function returns. You can use the defer keyword to create a deferred method, function, or anonymous function.

Syntax:

// 函数
defer func func_name(parameter_list Type) return_type{
    // 代码
}
// 方法
延迟 func (接收器 类型) 方法名(参数列表){
    // 代码
}
延迟 func (参数列表)(返回类型){
    // 代码
}

注意事项:

  • 在Go语言中,同一程序中允许多个延迟语句,并且它们按LIFO(后进先出)顺序执行,如示例2所示。

  • 在延迟语句中,将在执行延迟语句时(而不是在调用它们时)评估参数。

  • 延迟语句通常用于确保在完成文件处理后关闭文件,关闭通道或捕获程序中的紧急情况。

让我们通过示例来讨论这个概念:

示例1:

包 main
导入 "fmt"
// 函数
func mul(a1, a2 int) int {
    res := a1 * a2
    fmt.Println("结果:", res)
    返回 0
}
func show() {
    fmt.Println("Hello!, www.oldtoolbag.com Go语言基础教程")
}
func main() {
    //调用mul()函数
    //这里mul函数的行为
    //像普通函数一样
    mul(23, 45)
    //调用mul()函数
    //使用延迟关键字
    //这里是mul()函数
    //是延迟函数
    延迟 mul(23, 56)
    //调用show()函数
    show()
}

输出:

Result:  1035
Hello!, www.oldtoolbag.com Go语言基础教程
Result:  1288

用法说明:在上面的示例中,我们有两个名为mul()show()函数的函数。其中show()函数通常在main()函数中调用,同时我们以两种不同的方式调用mul()函数:

  • 首先,我们像常规函数一样调用mul函数,即mul(23,45)并在函数调用时执行(输出:结果:1035)。

  • 其次,我们使用延迟关键字将mul()函数称为延迟函数,即defer mul( 23,56),当所有周围的方法返回时,它将执行(输出:结果:1288)。

示例2:

包 main 
  
导入 "fmt"
  
// 函数
func add(a1, a2 int) int { 
    res := a1 + a2 
    fmt.Println("结果:", res) 
    返回 0 
} 
  
func main() { 
  
    fmt.Println("开始") 
  
    //多个延迟语句
    //按照 LIFO 顺序执行
    延迟 fmt.Println("结束") 
    延迟 add(34, 56) 
    延迟 add(10, 10) 
}

输出:

开始
Result:  20
Result:  90
End