【发布时间】:2018-04-10 19:29:53
【问题描述】:
我刚刚完成了围棋巡回赛,并开始了树行者练习。其明显的递归,但关闭通道是在最终弹出调用堆栈后的特殊情况。无论如何,我最终实现了它:
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
var walker func(t *tree.Tree, ch chan int)
walker = func(t *tree.Tree, ch chan int) {
if (t.Left != nil) {
walker(t.Left, ch)
}
ch <- t.Value
if (t.Right != nil) {
walker(t.Right, ch)
}
}
walker(t, ch)
close(ch)
}
到目前为止,我对 go 的印象是,如果可以的话,他们宁愿避免说话,所以在定义之前声明 var walker 似乎关闭。也许我错过了一些允许函数在没有声明的情况下引用自身的细节?如果可以的话就更好了:
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
func(t *tree.Tree, ch chan int) {
if (t.Left != nil) {
__me__(t.Left, ch)
}
ch <- t.Value
if (t.Right != nil) {
__me__(t.Right, ch)
}
}(t, ch)
close(ch)
}
这是一个简单的琐事问题,但我对这门语言还很陌生,我找不到答案...
【问题讨论】:
-
语言中没有这样的功能。看到这个:github.com/golang/go/issues/226
-
So far my impression of go is that they prefer to avoid saying things if they can这是一个奇怪的印象。大多数人观察到相反的情况,事实上,这与围棋的核心哲学完全相反,即“不要隐藏复杂性”。 -
@Flimzy,诚然,我对
go很陌生,但只是在参观,比如for (i := 0; i < 10; i++)->for i := 0; i < 10; i++->for ; sum < 1000;->for sum < 1000-> @ 987654332@, 和var thing := x*x; if x > 10->if v := x*x; x > 10... 这就是我的意思尽量避免说出来。无论如何,我明白你关于不要隐藏复杂性的观点。谢谢! -
@icza,是的,绝对是重复的。我的
googlingSkillz 让我失望了。感谢您指出。
标签: go