Declaration of "err" shadows declaration at


(Gonzalo Chumillas) #1

OK, I have the following code:

// Gets an environment variable and parse it.
expiration, err := time.ParseDuration(os.Getenv("expiration"))
if err != nil {
	panic(err)
}

// Gets an environment filename and verifies that it exists.
dbSource := os.Getenv("filename")
if _, err := os.Stat(dbSource); err != nil && os.IsNotExist(err) {
	panic(err)
}

But the second piece of code throws the following warning message:

declaration of “err” shadows declaration at ./main.go:33

It can be fixed quickly by replacing the second code by:

// Gets and environment filename and verifies that it exists.
dbSource := os.Getenv("filename")
// I changed ":=" by "="
if _, err = os.Stat(dbSource); err != nil && os.IsNotExist(err) {
	panic(err)
}

But doing it this way creates a dependency between the first and the second piece of code. I mean, if I remove the first piece of code the second code won’t work. And they are different things.

How would you solve this situation in a elegant way?


(George Calianu) #2

Declare err variable before

var err error

and use only err= in the rest of the code.


(Gonzalo Chumillas) #3

OK, the previous approach solves the problem. But this approach solves the issue as well:

dbSource := os.Getenv("filename")
info, err := os.Stat(dbSource)
if err != nil && os.IsNotExist(err) {
	panic(err)
}
// actually we don't need the info variable
fmt.Println(info)

The problem… the problem is that I don’t need the “info” variable. I would like to simply write:

dbSource := os.Getenv("dbSource")
_, err := os.Stat(dbSource)
if err != nil && os.IsNotExist(err) {
	panic(err)
}

But the previous code throws an error message. I would suggest the Golang team to change the notifications rules. Does it make sense?

**ADDITIONAL INFO: ** I solved the problem by renaming the err variable

dbSource := os.Getenv("dbSource")
if _, fileError := os.Stat(dbSource); fileError != nil {
	panic(fileError)
}