英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论