Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the closure scoping difference between short variable declarations and long ones in Go?

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?

like image 831
Joe Avatar asked Jul 08 '12 11:07

Joe


People also ask

What is difference between := and in Golang?

In Go, := is for declaration + assignment, whereas = is for assignment only. For example, var foo int = 10 is the same as foo := 10 .

Can short declaration := be used for defining global variables in go?

:= 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.

Where can the short variable declaration used in Golang?

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.

What does := mean in Golang?

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.


1 Answers

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.

like image 102
tux21b Avatar answered Sep 19 '22 11:09

tux21b