本文介绍了go中的"defer"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

golang的文档说:

golang's documentation says this:

这使我感到困惑.

问题:已评估"是否意味着该值已经已知?我只是不明白为什么两个例子打印的不同.这使我感到困惑.

Question: Does "evaluated" mean that the value is already known? I just don't understand why two examples print different. This confuse me.

我下面有两个例子:

 //It prints 0.
 func deferA() {
     i := 0
     defer fmt.Println(i)
     i++
     return
 }

 //It prints 1.
 func deferB() {
      i := 0
      defer func() {
          fmt.Println(i)
      }()
      i++
      return
 }

推荐答案

defer 采用一个函数,因此 fmt.Println(i)是一个函数,其参数 i 评估为 0 .

defer take a function, so fmt.Println(i) is a function and its argument i is evaluated as 0 when the defer statement is evaluated.

defer func(){fmt.Println(i)} func(){fmt.Println(i)} 不带参数,并且闭包,因此 i 不会被评估,但会被闭包关闭.

defer func() { fmt.Println(i) }, the func() { fmt.Println(i) } take no argument and its a closure, so i is not evaluated but close over by the closure.

您可以在 https://gobyexample.com/closures

这篇关于go中的"defer"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:58