Chapter 3. Composite Types

In the last chapter, we looked at simple types: numbers, booleans, and strings. In this chapter, we’ll learn about the composite types in Go, the built-in functions that support them, and the best practices for working with them.

Arrays—Too Rigid to Use Directly

Like most programming languages, Go has arrays. However, arrays are rarely used directly in Go. We’ll learn why in a bit, but first we’ll quickly cover array declaration syntax and use.

All of the elements in the array must be of the type that’s specified (this doesn’t mean they are always of the same type). There are a few different declaration styles. In the first, you specify the size of the array and the type of the elements in the array:

var x [3]int

This creates an array of three ints. Since no values were specified, all of the positions (x[0], x[1], and x[2]) are initialized to the zero value for an int, which is (of course) 0. If you have initial values for the array, you specify them with an array literal:

var x = [3]int{10, 20, 30}

If you have a sparse array (an array where most elements are set to their zero value), you can specify only the indices with values in the array literal:

var x = [12]int{1, 5: 4, 6, 10: 100, 15}

This creates an array of 12 ints with the following values: [1, 0, 0, 0, 0, 4, 6, 0, 0, 0, 100, 15].

When using an array literal to initialize an array, you can leave off the number and use … instead:

var x = [...]int{10, 20, 30}

You can use == and ...

Get Learning Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.