* [COFF] Shadowing variables in Go.
[not found] ` <202410011243.491ChKiV419651@freefriends.org>
@ 2024-10-01 13:20 ` Ralph Corderoy
0 siblings, 0 replies; only message in thread
From: Ralph Corderoy @ 2024-10-01 13:20 UTC (permalink / raw)
To: coff
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.
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2024-10-01 13:21 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
[not found] <CAKH6PiUS7RjkCyuYREFk4Li+aORaEZ_Vu7Dg1nnsFuHJF+mqog@mail.gmail.com>
[not found] ` <CAKzdPgwJ7-_BWztOQKiB6h5a+OGwXtefsD47Fq+GDwGGF7N4UA@mail.gmail.com>
[not found] ` <CAFH29tqBw0Qpzqv=21SUZonL7w_tpB0i4Ts8PwQ-Akn5PvTvVw@mail.gmail.com>
[not found] ` <CAKzdPgzQTjruZ3Cc-Sfram5M=jM+emvsTGR+7GRtZUUzNhZOCg@mail.gmail.com>
[not found] ` <20240930003630.GE17434@mcvoy.com>
[not found] ` <e23f7d87-1d17-f484-74ad-53deb5cc278f@makerlisp.com>
[not found] ` <d2d70aa8-0d7c-0a1e-9152-a4f8c50ae33d@makerlisp.com>
[not found] ` <202410011243.491ChKiV419651@freefriends.org>
2024-10-01 13:20 ` [COFF] Shadowing variables in Go Ralph Corderoy
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).