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


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?


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.

Answered By – Nick Craig-Wood

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *