[COFF] Shadowing variables in Go.
    Ralph Corderoy 
    ralph at inputplus.co.uk
       
    Tue Oct  1 23:20:59 AEST 2024
    
    
  
Taken to COFF...
Hi Arnold,
> In main(), I *think* I'm assigning to the global clientSet so that
> I can use it later.  But because of the 'err' and the :=, I've
> actually created a local variable that shadows the global one, and in
> otherfunc(), the global clientSet is still nil. Kaboom!
>
> The correct way to write the code is:
>
> 	var err error
> 	clientSet, err = cluster.MakeClient()	// or whatever
I think this is a common problem when learning Go, like assigning
getchar()'s value to a char in C.  It was back in ’14 anyway, when I saw
https://www.qureet.com/blog/golang-beartrap/ which has an ‘err’ at an
outer scope be unwritten by the ‘:=’ with the new, assigned-to ‘err’
going un-checked.
The author mentions ‘go vet’ highlights these cases with -shadow, which
is off by default.
https://pkg.go.dev/github.com/golangci/govet#hdr-Shadowed_variables
suggests that's still the case.
-- 
Cheers, Ralph.
    
    
More information about the COFF
mailing list