...

/

Using Arrays and Slices

Using Arrays and Slices

Learn about arrays and slices and their functionality in Go.

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.

%0 node_3 3 node_2 2 node_1 15 node_1673516498426 1 node_1673516478153 2
An array storing integers

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 ...