golang 延迟_了解Go中的延迟

golang 延迟

介绍 (Introduction)

Go has many of the common control-flow keywords found in other programming languages such as if, switch, for, etc. One keyword that isn’t found in most other programming languages is defer, and though it’s less common you’ll quickly see how useful it can be in your programs.

Go有许多共同的控制流的关键字在其他编程语言,如发现ifswitchfor等,未在其他大多数编程语言中的一个关键词是defer ,虽然这是不常见的,你会很快看到它在您的程序中有多有用。

One of the primary uses of a defer statement is for cleaning up resources, such as open files, network connections, and database handles. When your program is finished with these resources, it’s important to close them to avoid exhausting the program’s limits and to allow other programs access to those resources. defer makes our code cleaner and less error prone by keeping the calls to close the file/resource in proximity to the open call.

defer语句的主要用途之一是清理资源,例如打开的文件,网络连接和数据库句柄 。 当您的程序用完这些资源后,请务必关闭它们,以免耗尽程序的限制,并允许其他程序访问这些资源。 defer通过使关闭文件/资源​​的调用保持在打开调用附近,从而使我们的代码更整洁,并且更少出错。

In this article we will learn how to properly use the defer statement for cleaning up resources as well as several common mistakes that are made when using defer.

在本文中,我们将学习如何正确使用defer语句来清理资源以及使用defer时会犯的一些常见错误。

什么是defer声明 (What is a defer Statement)

A defer statement adds the function call following the defer keyword onto a stack. All of the calls on that stack are called when the function in which they were added returns. Because the calls are placed on a stack, they are called in last-in-first-out order.

defer语句将defer关键字后面的函数调用添加到堆栈中。 当添加了它们的函数返回时,将调用该堆栈上的所有调用。 由于这些调用位于堆栈上,因此将按照后进先出的顺序进行调用。

Let’s look at how defer works by printing out some text:

让我们通过打印一些文本来查看defer工作方式:

main.go
main.go
package main

import "fmt"

func main() {
    defer fmt.Println("Bye")
    fmt.Println("Hi")
}

In the main function, we have two statements. The first statement starts with the defer keyword, followed by a print statement that prints out Bye. The next line prints out Hi.

main函数中,我们有两个语句。 第一条语句以defer关键字开头,其后是一条print语句,该语句打印出Bye 。 下一行输出Hi

If we run the program, we will see the following output:

如果运行程序,将看到以下输出:


   
   
   
Output
Hi Bye

Notice that Hi was printed first. This is because any statement that is preceded by the defer keyword isn’t invoked until the end of the function in which defer was used.

请注意, Hi首先打印。 这是因为通过之前的任何声明defer关键字,则不会调用,直到该函数的最后defer使用。

Let’s take another look at the program, and this time we’ll add some comments to help illustrate what is happening:

让我们再看一下该程序,这次我们将添加一些注释以帮助说明正在发生的事情:

main.go
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值