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 .

Related Content


Slice expressions

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.


Clear

Clear The built-in function clear takes an argument of map, slice, or type parameter type, and deletes or zeroes out all elements [[Go 1.21(https://go.dev/ref/spec#Go_1.21)]]. Call Argument type Result clear(m) map[K]T deletes all entries, resulting in an empty map (len(m) == 0) clear(s) []T sets all elements up to the length of s to the zero value of T clear(t) type parameter see below clear is a relatively recent addition to Go, added just over a year ago.


Conversions from slice to array or array pointer

Conversions from slice to array or array pointer … Converting a slice to an array yields an array containing the elements of the underlying array of the slice. Similarly, converting a slice to an array pointer yields a pointer to the underlying array of the slice. In both cases, if the length of the slice is less than the length of the array, a run-time panic occurs. s := make([]byte, 2, 4) a0 := [0]byte(s) a1 := [1]byte(s[1:]) // a1[0] == s[1] a2 := [2]byte(s) // a2[0] == s[0] a4 := [4]byte(s) // panics: len([4]byte) > len(s) s0 := (*[0]byte)(s) // s0 !

Get daily content like this in your inbox!

Subscribe