Slice types

March 3, 2023

So we’ve learned about the fixed-length, and therefore somewaht limited, array types. Let’s now look at the more flexible cousin, the slice.

Slice types

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The number of elements is called the length of the slice and is never negative. The value of an uninitialized slice is nil.

SliceType = "[" "]" ElementType .

Okay, so what does that all mean?

It basically means that a slice can be thought of as a view into an underlying array.

Let me illustrate with an example:

	// Initialize a as an array of 10 integers
	var a = [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	// Initialize s as a slice "view" of a, of indexes 0, 1, and 2
	var s = a[0:3]
	fmt.Println(a, s) // Prints: [0 1 2 3 4 5 6 7 8 9] [0 1 2]

See this code in the playground

Quotes from The Go Programming Language Specification, Version of January 19, 2023


Share this

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

Unsure? Browse the archive .

Related Content


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.


Beware of array reuse with append

On Friday we looked at what happens when appending to a slice exceeds the capacity of the backing array. Today we’ll consider the alternative: What if the backing array can hold the new values? Appending to and copying slices … Otherwise, append re-uses the underlying array. Okay. That sounds pretty simple, doesn’t it? What’s to talk about? Well, this single sentence packs a lot of surprises. Consider this code: a := [.


Efficiently appending to slices

Yesterday we were introduced to the append function, which on the surface seems quite straight forward. But there are nuänces and gotchas! Appending to and copying slices … If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. You may recall from our (much) earlier discussion about slices and backing arrays, that a slice has not only a length (the number of elements it contains), but also a capacity—essentially the number of available elements in the backing array.

Get daily content like this in your inbox!

Subscribe