go中的"defer"是什么意思? [英] What is the meaning of 'defer' in go?

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

问题描述

golang的文档说:

golang's documentation says this:

在评估defer语句时,将评估延迟函数的参数.

A deferred function's arguments are evaluated when the defer statement is evaluated.

这使我感到困惑.

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

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)是一个函数,其参数<在评估defer语句时,将code> 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"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆