Go Slices

What is a Slice?

A slice is a dynamically-sized, flexible view into the elements of an array. Unlike arrays, you don't need to know the length at compile time.

arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // elements 20, 30, 40

Creating a Slice

You can create slices directly or from arrays:

Loading...
Output:

Unlike arrays, slices can grow dynamically with append.

Appending Elements

Use append() to grow a slice:

s := []int{1, 2}
s = append(s, 3, 4) // [1, 2, 3, 4]

You can also append another slice:

Loading...
Output:

Length and Capacity

A slice has both len() and cap():

Loading...
Output:

Capacity is the total space allocated; length is how many elements are initialized.

Underlying Array Sharing

Slices share the same underlying array. Modifying one affects others if they overlap:

Loading...
Output:

Copying Slices

Use the built-in copy function to avoid shared memory:

original := []int{1, 2, 3}
copyTo := make([]int, len(original))
copy(copyTo, original)

Nil vs Empty Slices

A nil slice has no underlying array; an empty slice has zero length but exists.

var a []int        // nil
b := []int{}       // empty

Use len() or compare to nil to check.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic