如何在延迟函数中延迟执行参数。

huangapple go评论80阅读模式
英文:

how to defer executing argument in defer function

问题

defer关键字用于在函数完成后调度一个函数调用。所以第一个打印函数fmt.Println("a ", Even())被延迟执行。但是由于参数在调用defer时被执行,Even()函数会立即被调用。

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())
}

输出结果为:

b  2
c  4
d  6
a  0

这是defer的工作原理。我只想知道是否有任何方法可以停止执行defer函数中的参数?

例如,在这种情况下,输出将为:

b 0
c 2
d 4
a 6

defer fmt.Println("a ", **Even()**)中的Even()函数将与Println一起执行。有没有办法做到这一点?

英文:

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?

答案1

得分: 3

如果将fmt.Println调用包装在另一个函数中(在这种情况下是一个匿名函数),则对Even()的评估将在其他对Even的调用完成后发生:

func main() {
    Even := MakeEvenNumber()

    defer func() {
        fmt.Println("a ", Even())
    }()

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

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())
}

huangapple
  • 本文由 发表于 2015年8月23日 22:55:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/32168017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定