Global variables and redeclaration

I have a small program that uses a global variable called files:

var files []string

In a function i used the following code:

	// filepath.Walk
	files, err := FilePathWalkDir(path)
	if err != nil {
		panic(err)
	}

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?

My understanding is that := declares new variables, where = would just handle an assignment.

You could declare err in advance, and then just use = for an assignment without declaring new variables.

files, err = FilePathWalkDir(path)

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?

Here’s the documentation from the language specification under Short Variable Declarations

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.

1 Like

Thank you, this was the explanation that I was looking for.

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