doulu6929
doulu6929
2015-01-31 13:28
浏览 108
已采纳

Golang嵌套函数内部的类

Go supports nested struct inside function but no nested function except lambda, does it mean there is no way to define a nested class inside function?

func f() {
    // nested struct Cls inside f
    type Cls struct {
    ...
    }
    // try bounding foo to Cls but fail
    func (c *Cls) foo() {
    ...
    }
}

Thus it feels a bit strange that class is weaken inside function.

Any hints?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwen7423
    dongwen7423 2015-01-31 13:33
    已采纳

    Actually it doesn't matter if you want to declare the function with or without a receiver: nesting functions in Go are not allowed.

    Although you can use Function literals to achieve something like this:

    func f() {
        foo := func(s string) {
            fmt.Println(s)
        }
    
        foo("Hello World!")
    }
    

    Here we created a variable foo which has a function type and it is delcared inside another function f. Calling the "outer" function f outputs: "Hello World!" as expected.

    Try it on Go Playground.

    点赞 评论

相关推荐