Lexical scope of variables needed by conditional choice select case

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?

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

1 Like

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!

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

1 Like

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

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