What are the problems that are mitigated by not allowing nested function declarations in Go?

corazza picture corazza · Feb 22, 2014 · Viewed 42.3k times · Source

Lambdas work as expected:

func main() {
    inc := func(x int) int { return x+1; }
}

However, the following declaration inside a declaration is not allowed:

func main() {
    func inc(x int) int { return x+1; }
}

For what reason are nested functions not allowed?

Answer

Nick Craig-Wood picture Nick Craig-Wood · Feb 23, 2014

I think there are 3 reasons why this obvious feature isn't allowed

  1. It would complicate the compiler slightly. At the moment the compiler knows all functions are at the top level.
  2. It would make a new class of programmer error - you could refactor something and accidentally nest some functions.
  3. Having a different syntax for functions and closures is a good thing. Making a closure is potentially more expensive than making a function so you should know you are doing it.

Those are just my opinions though - I haven't seen an official pronouncement from the language designers.