Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
corazza Avatar asked Feb 22 '14 22:02

corazza


People also ask

Does Go support nested functions?

Nested functions are allowed in Go. You just need to assign them to local variables within the outer function, and call them using those variables. Inner functions are often handy for local goroutines: func outerFunction(...)

Can a go function be created on the fly and used as values?

Function UsageFunctions can be created on the fly and can be used as values.

How do you write a function in Golang?

In Golang, we declare a function using the func keyword. A function has a name, a list of comma-separated input parameters along with their types, the result type(s), and a body. The input parameters and return type(s) are optional for a function. A function can be declared without any input and output.


2 Answers

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.

like image 58
Nick Craig-Wood Avatar answered Oct 14 '22 23:10

Nick Craig-Wood


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

func main() {     inc := func(x int) int { return x+1; } } 
like image 28
Matt Williamson Avatar answered Oct 15 '22 00:10

Matt Williamson