Skip to content
Openweb edited this page Nov 30, 2020 · 20 revisions

Go Slices

Slice is lightweight data-structure that provides access to sub-sequence of underlying array. It is defined as []T for element of type T. Multiple slices can have same underlying array. It has three elements:

  • Pointer to first element (not necessarily first element of underlying array)
  • Length of number if elements in slice
  • Capacity of number of elements a slice can hold.

Typically toSlice = append(toSlice, first, second, anotherSlice...) MAY copy underlying array to a new one with increase capacity, if it runs off space. Note that the returned toSlice may be different data structure than passed to append. For safety, unlike arrays, slices are NOT comparable. It means that we can-not apply == or != operators and can-not use them as map keys. However, to use []string slices as keys you can transform slices to a key type (e.g. string or struct) such that transform(slice) == transform(key).

Example

Create various slices over underlying space objects. Note that since all slices in this example are overlaying same array, if one of them over-writes a element, it will be reflected in all slices and array.

Slices overlaying array

// Underlying array: bodies: 13 of them
bodies := [...]string{"Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn",
                      "Uranus", "Neptune", "Pluto", "Haumea", "Makemake", "Gonggong"}
var planets []string = bodies[1:9] // Explicit []string slice, idx 9 not included
var inner []string                 // Inner planets, explicit, nil slice not defined yet
var outer []string                 // Outer planets, nil slice not defined yet
tno := bodies[9:13]                // Trans-Neptune objects, notice 13.

Go play slices overlying an array of space objects.

Notice that:

  1. Slices planets and inner have same pointer address.
  2. Array has same len() and cap()

Passed as reference

Note that slices are passed as a reference in Go. However note the s = append(s, item) usage returns a slice.

Strings and Byte arrays

Since strings are immutable in golang. To do operations on a string, it may first be converted to a []byte slice. Here is an example that picks anagrams in a array of words. See playground

Clone this wiki locally