Skip to Content
Learning Go
book

Learning Go

by Jon Bodner
March 2021
Beginner content levelBeginner
375 pages
8h 59m
English
O'Reilly Media, Inc.
Content preview from Learning Go

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 != to compare ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Go, 2nd Edition

Learning Go, 2nd Edition

Jon Bodner

Publisher Resources

ISBN: 9781492077206Errata PageSupplemental Content