Simple slice expression shortcuts

November 21, 2023

Simple slice expressions, which we started with yesterday, offer us two shortcuts:

Simple slice expressions

For convenience, any of the indices may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand:

a[2:]  // same as a[2 : len(a)]
a[:3]  // same as a[0 : 3]
a[:]   // same as a[0 : len(a)]

This should be pretty easy to understand. With the possible exception of the last one. Why would you ever omit both the low and high index?

Well, for one, this can be a convenient way to convert an array to a slice:

a := [5]int{1, 2, 3, 4, 5} // a is of type [5]int
s := a[:] // s is of type []int

If a is a pointer to an array, a[low : high] is shorthand for (*a)[low : high].

Although pointers to arrays are incredibly rare, we are given a convenient shorthand for slicing a pointer to an array.

a := [5]int{1, 2, 3, 4, 5}
ap := &a
s := ap[2:3] // equivalent to (*ap)[2:3], or in effect equivalent to a[2:3]

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 .