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?

3
  • 4
    struct is a struct type. Go doesn't have classes. Commented Jan 31, 2015 at 13:31
  • @icza sorry the class above means struct with bounding function. Forgive my incorrect expression. Commented Jan 31, 2015 at 13:35
  • Yes, I understood, I just corrected the term or terminology. Commented Jan 31, 2015 at 13:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

ok~ and is there a way to bound a Function literal to the nested struct?
@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).
what if i want to call this literal function recursively from inside itself?
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")
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.