duanjurong1347 2015-07-14 10:48
浏览 14
已采纳

推迟使用说明

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.

  • 写回答

2条回答 默认 最新

  • douwan7382 2015-07-14 11:16
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度