Golang嵌套类里面的函数

Hay*_*Pan 11 nested go

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尝试一下.

  • @schehata然后看看这个:[在Go中的函数内定义递归函数](/sf/ask/1966960901/ #28099510) (2认同)