Go core
Browse topics

Slice expressions and copying

Version
1.27
Review
Draft

Summary#

s[low:high] selects elements from low up to, but excluding, high. The result shares storage with s. In s[low:high:max], the result has capacity max - low and still shares that storage. copy and slices.Clone copy elements.

Syntax#

go
part := values[low:high]
limited := values[low:high:max]
n := copy(destination, source)
owned := slices.Clone(values)

Example#

go
package main

import (
	"fmt"
	"slices"
)

func main() {
	letters := []string{"a", "b", "c", "d", "e"}

	middle := letters[1:3]
	fmt.Println(middle, len(middle), cap(middle))
	middle[0] = "B" // also visible through letters
	fmt.Println(letters)

	limited := letters[1:3:3] // capacity 2
	limited = append(limited, "x")
	limited[0] = "changed" // now in separate storage
	fmt.Println(limited)
	fmt.Println(letters)

	short := make([]string, 2)
	n := copy(short, letters[2:])
	fmt.Println(n, short)

	owned := slices.Clone(letters[:2])
	owned[0] = "z"
	fmt.Println(owned, letters[:2])
}

Expected output#

Text
[b c] 2 4
[a B c d e]
[changed c x]
[a B c d e]
2 [c d]
[z B] [a B]

Common mistakes#

copy transfers only as many elements as the shorter slice holds, so copying into a nil or zero-length slice copies nothing. A small subslice can also keep a large backing array in memory. Clone the part you need to keep. Both copy methods are shallow.

Version applicability#

Two-index slices and copy date back to Go 1.0. Three-index slices require Go 1.2. The complete example requires Go 1.21 for slices.Clone.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0