Go支持嵌套struct里面的函数,但没有嵌套函数,除了lambda,是否意味着没有办法在函数内定义嵌套类?
func f() {
// nested struct Cls inside f
type Cls struct {
...
}
// try bounding foo to Cls but fail
func (c *Cls) foo() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
因此,类内部功能削弱感觉有点奇怪.
任何提示?
icz*_*cza 12
实际上,如果你想使用或不使用接收器声明函数并不重要:不允许在Go中嵌套函数.
虽然您可以使用函数文字来实现这样的事情:
func f() {
foo := func(s string) {
fmt.Println(s)
}
foo("Hello World!")
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们创建了一个foo
具有函数类型的变量,并在另一个函数内部进行了描述f
.调用"外部"函数f
输出:"Hello World!"
如预期的那样.
在Go Playground尝试一下.
归档时间: |
|
查看次数: |
6931 次 |
最近记录: |