Golang nested class inside function

前端 未结 1 612
时光取名叫无心
时光取名叫无心 2021-01-04 11:37

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          


        
相关标签:
1条回答
  • 2021-01-04 12:31

    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.

    0 讨论(0)
提交回复
热议问题