package private variables for singleton packages - good/bad style

125 views
Skip to first unread message

quin...@gmail.com

unread,
May 13, 2022, 4:23:20 AM5/13/22
to golang-nuts
Hi,

I have 3 years of experience writing go, but decades of writing C. I am reaching for best practices on using package private variables to implement signleton packages.

I work on a fairly large microservice project which uses protobufs over NATS for communication and ETCd for a key/val store etc. We have put together a repository of packages (a lbrary in C terms) of microservice support tools which mop up much common code in the microservices.

There is a precident for implementing such libraries using a package private variable to store the package's state (singletons) - the obvious example is log (https://cs.opensource.google/go/go/+/refs/tags/go1.18.2:src/log/log.go line 87, var std)

Doing this means our microservice code is a little cleaner but does hide some non-obvious "magic" in the library. The alternative is the microservices all need to create a set of global variables for the packages they reference and use those; which feels like unnecessary syntactic sugar.

I understand that this technique restricts the package to a single instance, however in this case this is fine; we never need more than one connection to NATS or ETCd.

I have read various blogs which argue one way or the other, do the Go authors (or any other esteemed authority) have any strong opinions to offer? Am I committing a crime against go, or am I using the power of the language to cleanly implement a feature?

-Steve

Ian Lance Taylor

unread,
May 13, 2022, 3:55:00 PM5/13/22
to quin...@gmail.com, golang-nuts
Go has global variables because sometimes it's easier to use a global
variable. The benefits and drawbacks are clear, and you already
mentioned them. Go is a pragmatic language. Make the right choice
for your environment. Using global variables is not a crime.

Ian
Reply all
Reply to author
Forward
0 new messages