Lexical scope of variables needed by conditional choice select case


(Øyvind Teig) #1

I have found no way to declare variables immediately above a select case.

Like in http://play.golang.org/p/RublOzUdhR the “input” variable seems to have to be declared above the for-loop, not just after select or even “best” just above the case.

It seems like variables input to by a channel in a case and used only within the case has to be more “global” than really necessary? What are the lexical scoping rules here?


(Jakob Borg) #2

It needs to be declared before (i.e., outside) the for loop, because you expect it to be in scope in the fmt.Println after the for loop. But it’s not actually used, because you are declaring other “input” variables in the select cases (shadowing). Also, you were adding unnecessary braces in the cases.

Simpler: http://play.golang.org/p/iT_yRXUba6


(Øyvind Teig) #3

I didn’t expect it to be in scope in the fmt.Println, but for some reason it complained that it was’nt used, so I threw it in there.

So, with the undeclared “input” it’s autodeclared and so actually in scope at the lowest possible level? I think I like it!


(Jakob Borg) #4

It’s not automatic; by using := you are declaring the variable. Did you check out the tour? It’s nice. :wink:


(Øyvind Teig) #5

So no I have a facit here: http://play.golang.org/p/Tbfgo6DFXA. I’ll check the tour, yes it looks nice. Thanks!


(system) closed #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.