and I realized that it was not using the global variable files, but rather it was redeclaring the variable files here. This led to a bug…
Of course, because of the err variable, I need the := here, but it was not my intention to redeclare files here.
I am really curious of why this is though, and how can I avoid it? Other than “DON’T USE GLOBAL VARIABLES!”, this is not production code, so in this case I didn’t care…
I eventually had to rewrite it like this to make it work (introducing a new variable called f)
// filepath.Walk
f, err := FilePathWalkDir(path)
if err != nil {
panic(err)
}
files = f
Is there another way to avoid redeclaration? Or is this the way to do it?
I understand what := does, I just felt that because the variable files already exists, it should not re-declare it. Well, at least that was what I thought, before I ran into this problem.
Now I do understand that it does not reuse the existing variable in my case above, but what about this case:
var files []string
files, err := FilePathWalkDir(path)
I need the := to declare the err variable. So what is the rule here?
Globally declared variables are re-declared, but locally declared variables are not?
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.