Skip to content

Go Slices

Slices are a key data type in Go, giving a more powerful interface to sequences than arrays. Unlike arrays, slices are typed only by the elements they contain (not the number of elements).

1. Creating Slices

An uninitialized slice is nil and has a length of 0.

package main
import "fmt"

func main() {
    // 1. Using make([]type, length)
    s := make([]string, 3)
    fmt.Println("emp:", s) // [  ]

    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)

    // 2. Slice Literal
    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)
}

2. The append Function

append returns a new slice containing one or more new values. It's the standard way to grow a slice.

1
2
3
4
s := []string{"a"}
s = append(s, "b")
s = append(s, "c", "d")
fmt.Println("apd:", s) // [a b c d]

3. Slicing Slices

Slices support a "copy" operator with the syntax slice[low:high]. This creates a new slice that points to a portion of the original.

1
2
3
l := s[2:5] // elements from index 2 to 4
l = s[:5]   // elements from index 0 to 4
l = s[2:]   // elements from index 2 to end

4. Copying Slices

To create an entirely new, independent copy of a slice, use the built-in copy function.

c := make([]string, len(s))
copy(c, s)

Length vs Capacity

  • Length: The number of elements currently in the slice. len(s)
  • Capacity: The number of elements the underlying array can hold before needing to reallocate. cap(s)

Summary: Array vs Slice

Feature Array Slice
Size Fixed (part of type) Dynamic (resizable)
Declaration [5]int []int
Passing Copied by value Passed by reference
Usage Rare Very Common