Search⌘ K
AI Features

Slices and Arrays

Explore how Go's slices and arrays function, their differences in memory handling, and why slices are preferred for flexible data management. Understand how passing slices affects underlying data and how to avoid common pitfalls with slicing.

We'll cover the following...

In Go, slices and arrays serve a similar purpose. They are declared nearly the same way:

Go (1.16.5)
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
array := [3]int{1, 2, 3}
// let the compiler work out array length
// this will be an equivalent of [3]int
array2 := [...]int{1, 2, 3}
fmt.Println(slice, array, array2)
}

Slices feel like arrays with useful functionality on top. They use pointers to arrays internally in their implementation. Slices however are so much more convenient that ...