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?


Solution 1:

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.

Solution 2:

Sure they are. You just have to assign them to a variable:

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

Solution 3:

Frequently Asked Questions (FAQ)

Why does Go not have feature X?

Every language contains novel features and omits someone's favorite feature. Go was designed with an eye on felicity of programming, speed of compilation, orthogonality of concepts, and the need to support features such as concurrency and garbage collection. Your favorite feature may be missing because it doesn't fit, because it affects compilation speed or clarity of design, or because it would make the fundamental system model too difficult.

If it bothers you that Go is missing feature X, please forgive us and investigate the features that Go does have. You might find that they compensate in interesting ways for the lack of X.

What would justify the complexity and expense of adding nested functions? What do yau want to do that you can't do without nested functions? Et cetera.