Go zero values finally hit me

mjb2kmn

MN Mark

Posted on February 12, 2019

Go zero values finally hit me

I decided to learn Go (not my first language) by opening the docs and an editor and just Going for it. After 2 weeks and a few hundred lines, I had a functional and useful tool and am mostly enjoying working with Go.

I had seen references to "zero values" here and there but didn't pay much attention. My variable definitions, assignments, flow control, and such were all working as expected so I didn't feel I was missing anything.
Then, suddenly, the idea of a Boolean variable's zero value being false penetrated my willful ignorance and I re-examined my code. What I found were lots of familiar patterns like this:

type Test struct {
    Pass    bool
}


if len(test.Passes) > 0 && len(test.Fails) == 0 {
    test.Pass = true
} else {
    test.Pass = false
}

But if a "zero value" means that simply declaring a variable name and type guarantees it gets initialized with a known value, then test.Pass was already false as soon as it existed. Meaning that all those else branches were redundant.

type Test struct {
    Pass    bool
}


if len(test.Passes) > 0 && len(test.Fails) == 0 {
    test.Pass = true
}

I was able to cut out a large portion of lines and simplify logic just by knowing and using the zero values of all the basic types.

After this I decided to not learn solely by the language specification and bought a book. The Go Programming Language book covers "zero values" within about the first dozen pages. (palm.Smack(&forehead))

The lesson here isn't only that Go's zero values make Go code more succinct, safe, and readable, but... well, I'm pretty sure there is another lesson in here. Maybe someone can spot it and explain it to me? ;)

💖 💪 🙅 🚩
mjb2kmn
MN Mark

Posted on February 12, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related