Arrays and Slices in Go: Working with Collections

January 23, 2024

Arrays and slices are important concepts in Go for working with collections of data. In this post, we will explore the fundamentals of arrays and slices, including how to declare, initialize, and manipulate these data structures. Additionally, we will cover common operations on arrays and slices, such as appending and slicing.

Arrays in Go

An array in Go is a fixed-size sequence of elements of the same type. To declare an array, you specify the type of its elements and the number of elements it can contain. Here’s an example of declaring an array of integers:

var numbers [5]int

In this example, we declare an array numbers that can hold 5 integers. Arrays in Go are zero-indexed, meaning the first element is at index 0 and the last element is at index n-1, where n is the length of the array.

You can initialize an array with values at the time of declaration:

var numbers = [5]int{1, 2, 3, 4, 5}

Accessing elements of an array is done using the index:

fmt.Println(numbers[0]) // Output: 1

Slices in Go

A slice is a flexible, dynamically-sized view into the elements of an array. Slices are more common and versatile than arrays in Go. To create a slice, you can use the make function or the slice literal syntax:

var s []int // using slice literal
s := make([]int, 5) // using make function

Unlike arrays, slices do not have a fixed size. You can append elements to a slice using the append function:

s = append(s, 6, 7, 8)

Slicing a slice allows you to create a new slice from a portion of an existing slice. The syntax for slicing is s[low:high], where low is the starting index and high is the ending index (exclusive):

slice := numbers[1:4] // Extracts elements at index 1, 2, 3

Understanding arrays and slices is crucial for working with collections of data in Go. By mastering these concepts, you will be well-equipped to handle a wide range of programming tasks.