Using Arrays and Slices
Learn about arrays and slices and their functionality in Go.
We'll cover the following...
Introduction
Languages require more than the basic types to hold data. The array
type is one of the core building blocks in lower-level languages, providing the base sequential data type. For most day-to-day use, Go's slice
type provides a flexible array that can grow as data needs grow and can be sliced into sections in order to share views of the data.
In this lesson, we'll discuss arrays as the building blocks of slices, the difference between the two, and how to utilize them in our code.
Arrays
The base sequential type in Go is the array (important to know but rarely used). Arrays are statically sized (if we create one that holds 10 int
types, it will always hold exactly 10 int
types).
Go provides an array type designated by putting [size]
before the type we wish to create an array of. For example, var x [5]int or x := [5]int{}
creates an array holding five integers indexed from 0
to 4
.
An assignment into an array is as easy as choosing the index. x[0] = 3
assigns 3 to index 0. Retrieving that value is as simple as ...