On Tue, Oct 10, 2017 at 7:22 AM, <etienne.da...@gmail.com> wrote: > > I'm trying to understand the scope of variables when using closures. > I wrote a simple program to compute fibonacci sequence with a closure (see > below). > Knowing that named return variables are initialized to 0 (when their type is > int), I tried to simplify my function ; but it doesn't compile, saying that > x is undefined. > I conclude that the scope of a return variable isn't the same as a "classic" > variable, but I don't understand why. > > Can you explain me the difference of scope between these two kind of > variables please? And the reason why they don't share the same scope? > > My program in the Go Playground: https://play.golang.org/p/KPWK9xoNNZ > > > const N = 10 > > func main() { > f := fibo() > for i := 0; i < N; i++ { > fmt.Println(f()) > } > } > > func fibo() func() int { > x, y := 0, 1 > return func() int { > defer func() { x, y = y, x+y }() > return x > } > } > > // fibo2 doesn't compile because x is undefined in the function returned. > //func fibo2() func() (x int) { > // y := 1 > // return func() int { > // defer func() { x, y = y, x+y }() > // return x > // } > //}
In the commented out code, x is a result variable, but only for `func() (x int)`. x is not a result variable for fibo2. To put it differently, within a func type literal such as `func() (x int)`, the scope of the parameters and results is restricted to the type literal itself. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.