From my reading of the spec:
A short variable declaration … is a shorthand for a regular variable
declaration with initializer expressions but no types…
I would have thought the two were identical:
var f func()
f = func() {
...
}
and
f := func() {
...
}
But it seems like they’re not. I was trying to wrap a self-recursive function inside of an outer function, but this works:
func myOuter() {
var f func()
f = func() {
f()
}
f()
}
But this doesn’t, saying undefined: f in the inner function.
func myOuter() {
f := func() {
f()
}
f()
}
So what is the difference?
Is there any way to write this with the short-form declaration or I do I have to write it out long-hand?
f := func() { /* ... */ }is identical tovar f func() = func() { /* ... */ }(but only the later one is allowed at the package level). In your specific case, neither of the two variants will work, since the statement will be evaluated from right to left. The solution is – as you have already suggested – to split the statement into two. One for declaring the variable and another for assigning the recursive function to it.