15

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?

fuz
  • 88,405
  • 25
  • 200
  • 352
Hayes Pan
  • 585
  • 1
  • 4
  • 19

2 Answers2

22

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 declared inside another function f. Calling the "outer" function f outputs: "Hello World!" as expected.

Try it on Go Playground.

icza
  • 389,944
  • 63
  • 907
  • 827
  • ok~ and is there a way to bound a Function literal to the nested `struct`? – Hayes Pan Jan 31 '15 at 13:39
  • @HayesPan No, you can't. Not in the sense of creating a method for the type. You could specifying an additional parameter to the function literal which would be of the `struct` type like the receiver, but it will not be a part of the `struct`'s method set. A _Function literal_ is not a _function_, it is just a _value_ (which has a function type). – icza Jan 31 '15 at 13:46
  • what if i want to call this literal function recursively from inside itself? – shehata May 08 '20 at 10:38
  • 2
    @schehata Then check out this: [Define a recursive function within a function in Go](https://stackoverflow.com/questions/28099441/define-a-recursive-function-within-a-function-in-go/28099510#28099510) – icza May 08 '20 at 11:03
0

I upvoted icza's answer but just to extend it a little, here's his example slightly modified, showing that variables defined in the outer function are visible to the inner function:

    func f(s string) {
        foo := func() {
            fmt.Println(s)
        }

        foo()
    }

    func main() {
        f("Hello, World!\n")
    }
Mike Gleen
  • 507
  • 5
  • 6