Issue
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.
Answered By – Nick Craig-Wood
Answer Checked By – Jay B. (BugsFixing Admin)