Golang nested class inner function

Go supports a nested inner function struct, but doesnโ€™t have a nested function other than lambda, does this mean that there is no way to define internally within a nested class?

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

So it seems a little strange that the class weakens inside the function.

Any clues?

+6
source share
1 answer

It doesn't really matter if you want to declare a function with or without a receiver: Go nesting functions 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 have created the variable foo , which has the type of the function and is divided inside another function f . Calling the "external" function f outputs: "Hello World!" , as was expected.

Try it on the go playground .

+7
source

Source: https://habr.com/ru/post/981805/


All Articles