HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
declarationsarefunctionproblemstheallowingmitigatednotthatnested

Problem

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

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

  • It would complicate the compiler slightly. At the moment the compiler knows all functions are at the top level.



  • It would make a new class of programmer error - you could refactor something and accidentally nest some functions.



  • 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.

Context

Stack Overflow Q#21961615, score: 79

Revisions (0)

No revisions yet.