cor*_*zza 71 declaration function go
编辑:如果不清楚我在问什么:不允许嵌套函数声明可以缓解哪些问题?
Lambdas按预期工作:
func main() {
inc := func(x int) int { return x+1; }
}
Run Code Online (Sandbox Code Playgroud)
但是,不允许在声明中使用以下声明:
func main() {
func inc(x int) int { return x+1; }
}
Run Code Online (Sandbox Code Playgroud)
出于什么原因,不允许使用嵌套函数?
Nic*_*ood 46
我认为有三个原因可以解释为什么不允许使用这个明显的功能
这些只是我的观点 - 我还没有看到语言设计师的正式声明.
Mat*_*son 26
当然可以.您只需将它们分配给变量:
func main() {
inc := func(x int) int { return x+1; }
}
Run Code Online (Sandbox Code Playgroud)
pet*_*rSO 23
每种语言都包含新颖的功能,并省略了某些人最喜欢的功能.Go的设计着眼于编程的幸福性,编译的速度,概念的正交性以及支持并发和垃圾收集等功能的需要.您最喜欢的功能可能会丢失,因为它不适合,因为它会影响编译速度或设计的清晰度,或者因为它会使基本系统模型太难.
如果您对Go缺少功能X感到困扰,请原谅我们并调查Go确实具有的功能.您可能会发现它们以缺乏X的有趣方式进行补偿.
什么能够证明添加嵌套函数的复杂性和费用是正确的?如果没有嵌套函数,你不能做什么?等等.
Koa*_*la3 12
package main
import "fmt"
func main() {
nested := func() {
fmt.Println("I am nested")
deeplyNested := func() {
fmt.Println("I am deeply nested")
}
deeplyNested()
}
nested()
}
Run Code Online (Sandbox Code Playgroud)
小智 11
Go 中允许嵌套函数。您只需要将它们分配给外部函数中的局部变量,并使用这些变量调用它们。
例子:
func outerFunction(iterations int, s1, s2 string) int {
someState := 0
innerFunction := func(param string) int {
// Could have another nested function here!
totalLength := 0
// Note that the iterations parameter is available
// in the inner function (closure)
for i := 0; i < iterations; i++) {
totalLength += len(param)
}
return totalLength
}
// Now we can call innerFunction() freely
someState = innerFunction(s1)
someState += innerFunction(s2)
return someState
}
myVar := outerFunction(100, "blah", "meh")
Run Code Online (Sandbox Code Playgroud)
内部函数对于本地 goroutine 来说通常很方便:
func outerFunction(...) {
innerFunction := func(...) {
...
}
go innerFunction(...)
}
Run Code Online (Sandbox Code Playgroud)