doudang1890 2015-08-23 14:55
浏览 37
已采纳

如何推迟执行延迟函数中的参数

This question already has an answer here:

defer in go schedules a function call to be run after the function completes. So 1st print function fmt.Println("a ", Even()) is defered. But as argument is executed when defer is called, Even() function is called immediately.

package main

import "fmt"

func MakeEvenNumber() func() int {
    num :=0
    return func() (ret int) {
        ret = num
        num = num + 2
        return ret
    }
}

func main() {

    Even := MakeEvenNumber()

    defer fmt.Println("a ", Even())

    fmt.Println("b ", Even())
    fmt.Println("c ", Even())
    fmt.Println("d ", Even())
}

Output:

b  2
c  4
d  6
a  0

This is happened in defer. I just want to know any way to stop executing argument in defer function?

like in this case, output will be:

b 0
c 2
d 4
a 6

defer fmt.Println("a ", **Even()**) this Even() function will be executed along with Println.

Any way to do this?

</div>
  • 写回答

1条回答 默认 最新

  • dtrvzd1171 2015-08-23 14:58
    关注

    If you wrap the fmt.Println call in another function (an anonymous function, in this case), the evaluation of Even() will happen after the other calls to Even have completed:

    func main() {
        Even := MakeEvenNumber()
    
        defer func() {
          fmt.Println("a ", Even())
        }()
    
        fmt.Println("b ", Even())
        fmt.Println("c ", Even())
        fmt.Println("d ", Even())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型