Slice capacity

March 7, 2023

Slice types

The array underlying a slice may extend past the end of the slice. The capacity is a measure of that extent: it is the sum of the length of the slice and the length of the array beyond the slice; a slice of length up to that capacity can be created by slicing a new one from the original slice. The capacity of a slice a can be discovered using the built-in function cap(a).

Let’s explore this capacity concept a bit by expanding our previous examples:

	var a = [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	var s = a[3:6]
	fmt.Println(a, s)           // Prints: [0 1 2 3 4 5 6 7 8 9] [3 4 5]
	fmt.Println(len(s), cap(s)) // Prints: 3 7

So here we see that the length of our slice s is 3, as expected. The capacity, however, is 7, indicating that the backing array has an additional 4 elements allocated into which the slice can expand, without allocating any additional memory. We can see this in action (and also further demonstrate that slices share storage with their backing array) with the following code:

	s = append(s, 99)
	fmt.Println(a, s)           // Prints: [0 1 2 3 4 5 99 7 8 9] [3 4 5 99]
	fmt.Println(len(s), cap(s)) // Prints: 4 7

See it in the playground.

A new, initialized slice value for a given element type T may be made using the built-in function make, which takes a slice type and parameters specifying the length and optionally the capacity. A slice created with make always allocates a new, hidden array to which the returned slice value refers. That is, executing

make([]T, length, capacity)

produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:

make([]int, 50, 100)
new([100]int)[0:50]

Here we see that the handy make function gives us the option to pre-allocate additional storage for a slice, in cases where we know we’ll need a slice of a particular size.

This is commonly useful when building a new slice by iterating over another slice or a map. This avoids re-allocating new arrays (and thus unncessarily taxing the garbage collector) every time the backing array’s capacity is exceeded. For example:

var ints = []int{1, 2, 3, 4, 5}

var strs = make([]string, 0, len(integers)) // Set strs to have the same capacity as ints' length
for _, i := range ints {
	strs = append(strs, strconv.Itoa(i))
}

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this

Related Content

Empty structs

We finally we have enough knowledge for the EBNF format not to seem completely foreign, so let’s jump back and take a look at that, with the examples provided in the spec… Struct types … StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . Tag = string_lit . // An empty struct.

Struct tags

Struct types … A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.

Struct method promotion

Yesterday we saw an example of struct field promotion. But methods (which we haven’t really discussed yet) can also be promoted. Struct types … Given a struct type S and a named type T, promoted methods are included in the method set of the struct as follows: If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.