Common bug in Go, maybe they did not resolve anything?

Variable shadowing, a common problem, no good solution in modern languages to avoid it.

C++ is not that bad!

With C++, and derivatives, you can shadow any one variable over and over again:

int var;

void myfunc()
    int var;

        int var;


In this example, I shadow the var variable twice within myfunc().

In itself, it doesn't hurt, but it is very often that when you do that, you did not mean to. That is, it's not unlikely that you reuse var within the function thinking it's the global variable or the first instance in myfunc() from the outermost block of the function.

I have two rules I follow in C++ for this kind of problems:

1. I nearly never make use of global variables, although my global variables start with g_ and local variables do not ever use that introducer.

2. I turn on the warning about shadowed variables and transform all warnings into errors:

... -Werror -Wshadow ...

So I'm pretty well protected against all sorts of issues.

What about Go on this one?

In Go, however, so far I haven't seen an anti-shadow feature for global variables. Today I had code like the following and the pointer would remain nil when I clearly allocated an object:

var (
  foo *Bar

func initFoo() {
    foo := new Bar()

The initFoo() function was allocating a new bar object, but it would not save it in the global variable. This is because of the colon (:) which creates a new variable under the hood. That init function was similar to:

    var foo *Bar
    foo = new Bar()

Now we'd clearly see that we're shadowing foo, I think.

Go is supposed to be there for you to avoid such errors but well, it looks like it has its pitfalls too. At least, it panics cleanly when you try to access a nil pointer so you can easily know where your mistake comes from.