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 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退