From my reading of the spec:
A short variable declaration ... is a shorthand for a regular variable declaration with initializer expressions but no types...
http://golang.org/ref/spec
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?
In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .
:= is known as the short declaration operator. It is used to declare and initialize the variables inside and outside the functions. It is used to declare and initialize the variables only inside the functions. Using this, variables have generally package level or global level scope.
Short Variable Declaration Operator(:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables.
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only. For example, var abc int = 20 is the same as abc := 20. It's useful when you don't want to fill up your code with type or struct declarations. Follow this answer to receive notifications.
f := func() { /* ... */ }
is identical to var 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.
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