err variable shadowing — is it a bad practice?

3,461 views
Skip to first unread message

iakov....@gmail.com

unread,
Nov 23, 2016, 5:46:26 AM11/23/16
to golang-nuts
Hi,
Occasionally go vet complains about shadowing of the err variable.
Consider the following code.

package main

import (
"flag"
"io"
"os"
)

func main() {
inFilename := flag.String("in", "infile", "input file")
outFilename := flag.String("out", "outfile", "output file")
flag.Parse()

in, err := os.Open(*inFilename)
if err != nil {
panic(err)
}

out, err := os.Create(*outFilename)
if err != nil {
panic(err)
}

buf := make([]byte, 1024)
for {
n, err := in.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
if _, err := out.Write(buf[:n]); err != nil {
panic(err)
}
}
}


Go vet in strict mode complains:

$ go tool vet -shadow -shadowstrict ./cat.go 
./cat.go:26: declaration of "err" shadows declaration at ./cat.go:14
./cat.go:33: declaration of "err" shadows declaration at ./cat.go:26

Is it really a bad practice? What's the alternative?
Declaring all the variables in advance with explicitly specifying their types, i.e.

var out *os.File
out, err = os.Create(*outFilename)
?

Thanks,
Iakov

Dave Cheney

unread,
Nov 23, 2016, 6:30:49 AM11/23/16
to golang-nuts
This is extremely common in go code, vet is being pedantic,

Steven Hartland

unread,
Nov 23, 2016, 6:52:21 AM11/23/16
to golan...@googlegroups.com
I believe vet shadow is known to have issues and is quite picky ;-)

Your first one I'd say could be classed as bug as you're clearly declaring n however I'd guess this is due to the for loop as declaring n out of the loop eliminating the short declaration will fix it. This is confirmed by eliminating the for which also eliminates the warning.

Your second warning (cat.go:33) I'd say is correct as you don't declare a new variable hence err is declared unnecessarily. I'm not sure if go will actually redeclare a new var under the hood, but as err is already available just reuse it.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages