推迟使用说明 [英] Defer usage clarification

查看:102
本文介绍了推迟使用说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下功能:

pre $ func printNumbers(){
var x int

推迟fmt.Println(x)

为i:= 0;我< 5; i ++ {
x ++
}
}

规范中:


每次执行defer语句时,调用的函数值和参数将照常进行评估并重新保存,但实际函数不会被调用。


显然,函数执行结束时会打印出零。
但是,如果我想打印出变量 x

的最终值,我该怎么办?

我提出了以下解决方案:

pre $ func printNumbers(){
var x int

printVal:= func(){
fmt.Println(x)
}

推迟printVal()

for i:= 0;我< 5; i ++ {
x ++
}
}

有一个更好的方法来解决这个问题。

解决方案

如果推迟有参数,声明;这在下面的片段中说明,其中延期将打印0:

  func printNumber(){
i:= 0
defer fmt.Println(i)//会打印0
i ++
return
}

如果您想延迟执行语句或函数,直到封闭(调用)函数结束,您可以使用匿名函数作为推迟语句。这里是一个更新的例子:

  func printNumbers(){
x:= 0
defer func() {fmt.Println(x)}()
for i:= 0;我< 5; i ++ {
x ++;
}
return
}

http://play.golang.org/p/YQGQ_8a0_9


Let's assume I have the following function

func printNumbers(){
 var x int

 defer fmt.Println(x)

 for i := 0; i < 5; i++{
  x++
 }
}

As it is said in the specification:

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

Obviously, zero will be printed out when the function execution ends. But what should I do if I want to print out the final value of variable x?

I've come up with the following solution:

func printNumbers(){
  var x int

  printVal := func(){
    fmt.Println(x)
  }

  defer printVal()

  for i := 0; i < 5; i++{
    x++
  }
}

So I wonder if there is a better way to resolve this problem.

解决方案

If the defer has arguments they are evaluated at the line of the defer-statement; this is illustrated in the following snippet, where the defer will print 0:

func printNumber() {
   i := 0
   defer fmt.Println(i) // will print 0
   i++
   return
}

You can use an anonymous function as a defer statement if you want to postpone the execution of a statement or a function until the end of the enclosing (calling) function. Here is an updated example:

func printNumbers() {
    x := 0
    defer func() { fmt.Println(x) }()
    for i:=0; i < 5; i++ {
        x++;
    }
    return
}

http://play.golang.org/p/YQGQ_8a0_9

这篇关于推迟使用说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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