WOW! I can’t believe I didn’t know this.
Today I learned that standard function definitions inside of golang functions (a.k.a. nested functions) aren’t allowed but this can be bypassed by using lambda-esque function syntax.
I was curious as to why standard nesting wasn’t allowed.
func a() error {
func b() error {
// ...
}
if err := b(); err != nil {
// ... Do something
return err
}
// .. Do something else
return nil
}
Then I found a stackoverflow thread , which is really a mess of opinions surrounding “You clearly have a workaround. Use it.” where people were trying to backtrack from opinions from a github issue from 2007 on the golang/go repository that was closed due to age (i mean obviously).
Status changed to WontFix in 2009 FrozenDueToAge added in 2016 Russ Cox detached himself from issue
So, it’s ok right? Kinda. I mean one can use this lambda/anonymous function workaround and call it a day.
What’s scraping my knee is that there is no official statement on this specific thing. Perhaps even a vague reasoning that there is a slight compilation performance issue to support this. Or Maybe that it’s a conscious choice by the developers of go.
I’m going to end this rant with this FAQ answer from the official go website.
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.
Oh by the way, if you’re still looking for the solution to this problem, here you go!
func a() error {
// lambda-esque function definition
b := func() error {
// ...
}
if err := b(); err != nil {
// ... Do something
return err
}
// .. Do something else
return nil
}