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?
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(...)
Function UsageFunctions can be created on the fly and can be used as values.
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.
I think there are 3 reasons why this obvious feature isn't allowed
Those are just my opinions though - I haven't seen an official pronouncement from the language designers.
Sure they are. You just have to assign them to a variable:
func main() { inc := func(x int) int { return x+1; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With