On Fri, May 13, 2022 at 1:23 AM quin...@gmail.com <quint...@gmail.com> wrote:
>
> 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?

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

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcV6Jg5D--W4vUy_0Non6Sow5K4VsrcBP%3D%3DA8QM2cx3XQA%40mail.gmail.com.

Reply via email to