Golang: Slices 101.

Glitch
3 min readMar 12, 2023

--

In Go, a slice is a dynamically-sized, flexible view into the elements of an array. Slices are a powerful feature of the language and are used extensively in Go programs. In this blog post, we will explore what slices are, how they work, and how to use them effectively in your Go code.

What are slices?

A slice is a lightweight data structure that allows you to work with a flexible sequence of elements. It is similar to an array, but with two key differences:

Slices are dynamically-sized: The size of a slice can grow or shrink as needed. This makes them very flexible and convenient to use.

Slices are a view into an array: Slices do not store any data themselves. Instead, they provide a view into the underlying array. This means that when you modify a slice, you are also modifying the underlying array.

Here's how you can create a slice in Go:

// Create a slice with three elements a := []int{1, 2, 3}

This creates a slice a with three elements: 1, 2, and 3. The []int syntax indicates that we are creating a slice of int values.

Slicing syntax

Go provides a powerful slicing syntax that allows you to extract a portion of a slice. The syntax is as follows:

a[start:end]

This creates a new slice that contains the elements of a from index start to index end-1. For example:

a := []int{1, 2, 3, 4, 5} // Create a new slice from index 1 to index 3 (excluding index 3) b := a[1:3] // b = [2, 3]

Modifying slices

Slices are a view into an array, which means that when you modify a slice, you are also modifying the underlying array. This can sometimes lead to unexpected behavior if you're not careful. Here's an example:

a := []int{1, 2, 3, 4, 5} // Create a new slice from index 1 to index 3 (excluding index 3) b := a[1:3] // b = [2, 3] // Modify the second element of the new slice b[1] = 100 // The original slice has also been modified // a = [1, 2, 100, 4, 5]

As you can see, modifying b also modified the original slice a. If you want to create a new slice that is completely independent of the original slice, you can use the copy function:

a := []int{1, 2, 3, 4, 5} // Create a new slice with the same length as the original slice b := make([]int, len(a)) // Copy the elements of the original slice to the new slice copy(b, a) // Modify the second element of the new slice b[1] = 100 // The original slice has not been modified // a = [1, 2, 3, 4, 5]

Working with slices

Slices are a powerful feature of the Go language that allow you to work with flexible sequences of elements. Here are a few tips for working with slices effectively:

Use the make function to create a new slice with a specified length and capacity.

--

--

No responses yet