如何在Go中递归调用闭包?

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

How to recurse a closure in Go?

问题

如何在Go中递归一个闭包?

假设我有一个闭包,像这样:

recur := func(){
	recur()
}

编译器报错:

> undefined: recur

我该如何实现它?为什么会发生这种情况?

英文:

How to recurse a closure in Go?

Suppose I have a closure like

recur := func(){
	recur()
}

Compiler says:

> undefined: recur

How can i implement it? Why is it happening?

答案1

得分: 25

这是翻译好的内容:

这是因为评估顺序的工作方式导致的。

截至2015年12月(go.1.5.1),没有任何语言特性提供此功能。

可能的解决方法:

var recur func()
recur = func(){
	recur()
}

//或者

type recurF func(recurF)

recur := func(recur recurF) {
	recur(recur)
}

更多信息:https://github.com/golang/go/issues/226

英文:

it happens because of how the order of evaluation works.

As of December 2015 (go.1.5.1), there isn't any language feature providing it.

Possible workarounds:

var recur func()
recur = func(){
	recur()
}

//or

type recurF func(recurF)

recur := func(recur recurF) {
	recur(recur)
}

More Info: https://github.com/golang/go/issues/226

huangapple
  • 本文由 发表于 2015年12月10日 14:00:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/34194762.html
匿名

发表评论

匿名网友

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

确定