Converting Between Slices and Arrays
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]) // THEThis 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]) // theExtra 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.
The shortcut
For every conversion, ask two questions: "does it copy or share?" and "can it be too short?" arr[:]: shares, never too short. [N]T(s): copies, panics if len(s) < N.
The data
rankedis[]string{"hello", "world"}, len 2.
Drills
Answer fast — trust the rule.
arr := [3]int{1, 2, 3}; s := arr[:]; s[1] = 20. What is arr?
s := []int{1, 2, 3, 4}; a := [2]int(s). What is a?
s := []int{1, 2}; a := [3]int(s). What happens?
s := []int{1, 2, 3}; a := [3]int(s); s[0] = 9. What is a[0]?
var a [3]int; n := copy(a[:], []int{5, 6}). What is n?
Remember
- Array to slice shares; slice to array copies, and needs enough elements.
- Shortcut: ask "copy or share?" and "can it be too short?"
- Trap:
[N]T(s)panics on a short slice; guard with a length check or usecopy.
