DEV Community

MN Mark
MN Mark

Posted on

5 2 1 1 1

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? ;)

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
rhymes profile image
rhymes

Maybe someone can spot it and explain it to me? ;)

That going through a tutorial is worth it :D

by the way you can further simplify that with:

test.Pass = len(test.Passes) > 0 && len(test.Fails) == 0

:D

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more