Skip to the workspace
Pebellslearn by building
Arrays & Slices  ›  Capstone Project

Converting Between Slices and Arrays

Slice to Array Conversion 14 minSlicing an array with arr[:] gives a slice that shares the array's memory, while converting a slice to an array type copies its first elements and panics if the slice is too short.

golang / Converting Between Slices and Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Converting Between Slices and Arrays

Slicing an array with arr[:] gives a slice that shares the array's memory, while converting a slice to an array type copies its first elements and panics if the slice is too short.

Compare copies and shared views when moving between array and slice representations.

tally ranks words in a slice, because the number of distinct words is unknown. The podium, though, is a fixed [3]string. Moving data between the two is simple, but one direction shares memory and the other copies — and mixing them up changes what your program prints.

The rule

Array to slice shares; slice to array copies, and needs enough elements.

Array → slice: arr[:]. Slicing an array gives a slice whose underlying array is that array. No copy is made:

podium := [3]string{"the", "cat", "sat"}
view := podium[:]            // len 3, cap 3, same memory
view[0] = "THE"
fmt.Println(podium[0])       // THE

This is how you hand an array to the many functions that take slices, such as strings.Join(podium[:], ", ") or sort.Strings(podium[:]), which then sorts the array in place.

Slice → array: [N]T(s) (Go 1.20 and later). It creates a new array and copies the first N elements:

ranked := []string{"the", "cat", "sat", "mat"}
top := [3]string(ranked)   // [the cat sat], a copy
ranked[0] = "a"
fmt.Println(top[0])        // the

Extra elements are ignored, but if the slice has fewer than N elements the conversion panics at run time. Guard it:

if len(ranked) >= 3 {
	top = [3]string(ranked)
}

Why would you want an array at all, once you have a slice? Arrays are comparable and can be map keys, so [3]string can key a map of three-word phrases, and a fixed size documents intent in a function signature.

Two relatives are worth knowing:

  • (*[3]string)(ranked) converts to an array pointer, which shares memory instead of copying (same length rule).
  • copy(top[:], ranked) copies as many elements as fit and never panics; it returns how many it copied.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.