Little Nellie Image from WikiMedia

A License to Initialize

A Go Brain Teaser

Miki Tebeka
2 min readMay 13, 2022

--

https://pragprog.com/newsletter/

What will will the following code print? Will it even compile?

This code will compile and print: [0 0 7]. What is going on here?

Let’s take a look at another code snippet:

I would guess that the output in this example is less surprising for you. You can initialize struct fields by name and Go will set the uninitialized fields to their zero value.

Let’s go back to our original code. v is an array, not a slice. Normally arrays are initialized with a size, for example arr := [3]int{}. But you can specify instead of the size, and then the Go compiler will figure out the size. For example:

What we do in the original code is to initialize the array by index. We tell the Go compiler: “Create an int array and initialize the third element to 7”. The compiler will create an array with three elements and will initialize the first two to their zero value, which is 0.

Go is a simple language, yet it provides many ways to initialize variables. Using the appropriate initialization method will lead to shorter and clearer code. In this teaser case, see how the new netip package is using it to write concise test cases.

--

--