迷彩 潜伏 隐蔽 伪装
分类: 信息化
2013-08-22 14:34:40
package main
func main() {
var sum func(int) intsum = func(n int) int {
if n == 1 {
return 1
}return n + sum(n - 1)
}println(sum(5))
}
有人会抱怨说,如果sum变量会改了怎么办?例如以下程序会崩溃:
package main
func main() {
var sum func(int) int
sum = func(n int) int {
if n == 1 {
return 1
}return n + sum(n - 1)
}}f, sum := sum, nilprintln(f(5))
解决方案是外面再包一层匿名函数:
package main
func main() {
sum := func(n int) int {
var sum func(int) intsum = func(n int) int {
if n == 1 {
return 1
}return n + sum(n - 1)
}return sum(n)
}f, sum := sum, nilprintln(f(5))
}
为什么go语言不直接支持这个特性呢?Russ Cox给出了一个解释[1]:
We've written >100k lines of Go code and it has come up maybe once. That kind of frequency doesn't suggest that a language change is warranted.
意思就是说,在实际编码中遇到需要这种特性的几率很小很小,所以没有必要直接在语言层面去支持,如果偶然遇到就使用替代方案吧。
[1]