Slice expressions

November 20, 2023

Last week’s livestream turned out to be a bit of a disappointment, as some Docker problems prevented me from making any real progress. I’ve resolved that, so today I hope to hit the ground running with some Kubernetes deployments! I hope you can join me again today on my live stream.

Ever wonder why Go uses the terminology “slice”, rather than “array”, to refer to a variable list of things? Today’s section explains that.

Slice expressions

Slice expressions construct a substring or slice from a string, array, pointer to array, or slice. There are two variants: a simple form that specifies a low and high bound, and a full form that also specifies a bound on the capacity.

In other words, we can “slice” strings, arrays, and slices. Think of it as slicing off the beginning and/or end of the original type, and returning a “slice” of that original.

Simple slice expressions

The primary expression

a[low : high]

constructs a substring or slice.

Let’s talk about this first.

In general, slice expressions work on arrays/slices, and return slices. As a special case, though, if you’re slicing a string, you get a string back, not a slice, as you might otherwise expect.

str := string("Hello, World")
arr := [10]int{1, 2, 3, 4, 5, 6}
fmt.Printf("%T %T\n", str[3:6], arr[2:4]) // Prints: string []int

… The core type of a must be a string, array, pointer to array, slice, or a bytestring. The indices low and high select which elements of operand a appear in the result. The result has indices starting at 0 and length equal to high - low. After slicing the array a

a := [5]int{1, 2, 3, 4, 5}
s := a[1:4]

the slice s has type []int, length 3, capacity 4, and elements

s[0] == 2
s[1] == 3
s[2] == 4

With the exception of slicing a string, as mentioned above, the resulting type is a slice of the input type’s element:

ary := [5]int{1, 2, 3, 4, 5}
slc := []int{1, 2, 3, 4, 5}
ptr := &ary

x := ary[1:4] // x, y, and z all
y := slc[1:4] // have the same
z := ptr[1:4] // type of []int

fmt.Printf("%T %T %T\n", x, y, z) // Prints: []int []int []int

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .