您的位置 首页 golang

「GCTT 出品」Go 系列教程——29. Defer

「GCTT 出品」Go 系列教程——29. Defer

什么是 defer?

defer 语句的用途是:含有 defer 语句的函数,会在该函数将要返回之前,调用另一个函数。这个定义可能看起来很复杂,我们通过一个示例就很容易明白了。

示例

「GCTT 出品」Go 系列教程——29. Defer

上面的程序很简单,就是找出一个给定切片的最大值。largest 函数接收一个 int 类型的 切片 作为参数,然后打印出该切片中的最大值。largest 函数的第一行的语句为 defer finished()。这表示在 finished() 函数将要返回之前,会调用 finished() 函数。运行该程序,你会看到有如下输出:

「GCTT 出品」Go 系列教程——29. Defer

largest 函数开始执行后,会打印上面的两行输出。而就在 largest 将要返回的时候,又调用了我们的延迟函数(Deferred Function),打印出 Finished finding largest 的文本。

延迟方法

defer 不仅限于 函数 的调用,调用 方法 也是合法的。我们写一个小程序来测试吧。

「GCTT 出品」Go 系列教程——29. Defer

在上面的例子中,我们在第 22 行延迟了一个方法调用。而其他的代码很直观,这里不再解释。该程序输出:

Welcome John Smith
 

实参取值(Arguments Evaluation)

在 Go 语言中,并非在调用延迟函数的时候才确定实参,而是当执行 defer 语句的时候,就会对延迟函数的实参进行求值。

通过一个例子就能够理解了。

「GCTT 出品」Go 系列教程——29. Defer

在上面的程序里的第 11 行,a 的初始值为 5。在第 12 行执行 defer 语句的时候,由于 a 等于 5,因此延迟函数 printA 的实参也等于 5。接着我们在第 13 行将 a 的值修改为 10。下一行会打印出 a 的值。该程序输出:

「GCTT 出品」Go 系列教程——29. Defer

从上面的输出,我们可以看出,在调用了 defer 语句后,虽然我们将 a 修改为 10,但调用延迟函数 printA(a)后,仍然打印的是 5。

defer 栈

当一个函数内多次调用 defer 时,Go 会把 defer 调用放入到一个栈中,随后按照后进先出(Last In First Out, LIFO)的顺序执行。

我们下面编写一个小程序,使用 defer 栈,将一个 字符串 逆序打印。

「GCTT 出品」Go 系列教程——29. Defer

在上述程序中的第 11 行,for range 循环会遍历一个字符串,并在第 12 行调用了 defer fmt.Printf(“%c”, v)。这些延迟调用会添加到一个栈中,按照后进先出的顺序执行,因此,该字符串会逆序打印出来。该程序会输出:

Orignal String: Naveen 
Reversed String: neevaN
 

defer 的实际应用

目前为止,我们看到的代码示例,都没有体现出 defer 的实际用途。本节我们会看看 defer 的实际应用。

当一个函数应该在与当前代码流(Code Flow)无关的环境下调用时,可以使用 defer。我们通过一个用到了 WaitGroup 代码示例来理解这句话的含义。我们首先会写一个没有使用 defer 的程序,然后我们会用 defer 来修改,看到 defer 带来的好处。

「GCTT 出品」Go 系列教程——29. Defer

在上面的程序里,我们在第 8 行创建了 rect 结构体 ,并在第 13 行创建了 rect 的方法 area,计算出矩形的面积。area 检查了矩形的长宽是否小于零。如果矩形的长宽小于零,它会打印出对应的提示信息,而如果大于零,它会打印出矩形的面积。

main 函数创建了 3 个 rect 类型的变量:r1、r2 和 r3。在第 34 行,我们把这 3 个变量添加到了 rects 切片里。该切片接着使用 for range 循环遍历,把 area 方法作为一个并发的 Go 协程进行调用(第 37 行)。我们用 WaitGroup wg 来确保 main 函数在其他协程执行完毕之后,才会结束执行。WaitGroup 作为参数传递给 area 方法后,在第 16 行、第 21 行和第 26 行通知 main 函数,表示现在 协程 已经完成所有任务。 如果你仔细观察,会发现 wg.Done() 只在 area 函数返回的时候才会调用。wg.Done() 应该在 area将要返回之前调用,并且与代码流的路径(Path)无关,因此我们可以只调用一次 defer,来有效地替换掉 wg.Done() 的多次调用

我们来用 defer 来重写上面的代码。

在下面的代码中,我们移除了原先程序中的 3 个 wg.Done 的调用,而是用一个单独的 defer wg.Done() 来取代它(第 14 行)。这使得我们的代码更加简洁易懂。

「GCTT 出品」Go 系列教程——29. Defer

该程序会输出:

「GCTT 出品」Go 系列教程——29. Defer

在上面的程序中,使用 defer 还有一个好处。假设我们使用 if 条件语句,又给 area 方法添加了一条返回路径(Return Path)。如果没有使用 defer 来调用 wg.Done(),我们就得很小心了,确保在这条新添的返回路径里调用了 wg.Done()。由于现在我们延迟调用了 wg.Done(),因此无需再为这条新的返回路径添加 wg.Done() 了。

本教程到此结束。祝你愉快。

上一教程 –

下一教程 – 错误处理


历史文章:

文章来源:智云一二三科技

文章标题:「GCTT 出品」Go 系列教程——29. Defer

文章地址:https://www.zhihuclub.com/88746.shtml

关于作者: 智云科技

热门文章

评论已关闭

36条评论

  1. Shop around for Cialis online drugstores online to save some money It may be dangerous

  2. The medication starts showing effects within 30 minutes and lasts as long as 36 hours

  3. Viagra is a safe and effective treatment for erectile dysfunction when taken as directed by a healthcare provider 5mg or 5mg dose, and Cialis used as-needed is generally the 10mg or 20mg dose

  4. The process of getting generic Viagra locally can be long, embarrassing, and a huge hassle

  5. Gutman and colleagues reviewed data from 198, 164 pregnancies of U. erythromycin stearate decreases effects of cefuroxime by pharmacodynamic antagonism.

  6. Clinical Investigation Centre, Faculty of Medicine, University of Malaya, Kuala Lumpur, 50603, Malaysia But we know SEs are cumulative and I ll see what happens down the road

  7. Alzheimer found have become the definitive diagnostic finding to distinguish Alzheimer s disease from multi infarct dementia Mia zSuVCLyCjnYPRIdvfLL 6 6 2022

  8. 056 at P60 measurement, Fig 7H albuterol isosorbide mononitrate er 30 mg picture A study by Professor Sir Brian Jarman, the world expert on hospital performance, calculated over the past three years there had been 526 excess deaths at the trust over the last three years, above what would be considered the norm

  9. In patients who are in clinical complete remission, increases in CA 125 from their initial treatment represent the most common method to detect disease that will eventually relapse clinically You could try exfoliating body scrub or just a loofah

  10. Additional studies using the same overall experimental design showed that treatment with BZA along with 1

  11. erectosil para que sirve ciprofloxacino de 500 mg Pope Francis donned a Mexican sombrero as he met the faithful on Copacabana Beach in Rio De Janeiro

  12. 03; odds ratio 95 confidence interval 3 Unenhanced T2 weighted T2 axial, T2 sagittal, and T1 weighted T1 axial sequences are acquired

  13. Phenylephrine eye drops are used to dilate the pupils to enable fundoscopy and is used in neonates when an ophthalmic examination is conducted to assess the presence of retinopathy of prematurity Programming and inheritance of parental DNA methylomes in mammals

  14. That is, consciousness is fundamental, and it is because of this that there will be how fast can apple cider vinegar lower blood pressure stop taking blood pressure pills problems with consciousness, and animalization will occur cialis lamisil krem eczane fiyat Such a move would have made it easier for banks that werecaught wrong footed by the spike in bond yields in late May tohedge their portfolios by reducing the need to sell bonds tobalance their books, potentially dampening market swings

  15. Truth in science requires only one scientist to verify reproducible results in the face of pharmaceutical tyranny The 6 were the ones my The 6 were the ones my oncologist said were NOT to be taken with tamox

  16. The effectiveness of intravenous ketamine and lidocaine on peripheral neuropathic pain I find if i skip a day it eases a tad but i am not sure i want to stay this way long term

  17. American Association of Clinical Endocrinologists medical guidelines for clinical practice for growth hormone use in adults and children 2003 update

  18. Fifteen studies reported on ECLS for drowning associated with accidental hypothermia 20, 22, 23, 24, 31, 34, 35, 43, 44, 45, 46, 48, 49, 50, 51 The core curriculum consists of human gross anatomy, microscopic anatomy, and neuroanatomy

网站地图