Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go cap() function

Reference for Go cap(): the capacity of a slice, array, pointer to array or channel, how slicing changes it, and how it differs from len().

cap returns the capacity of its argument. For a slice, that is the number of elements the slice can hold, counting from its first element, before append has to allocate a new array. For an array or a pointer to an array it equals the length. For a channel it is the buffer size.

Capacity is always at least the length. cap does not work on strings or maps; use len for those.

Go
s := make([]int, 2, 10)
fmt.Println(len(s), cap(s)) // 2 10

Try it

Go Capacity changes with slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Watching append grow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func cap(v Type) int
Argument type Result
Array [n]T or pointer to array n (constant if the expression has no function calls or channel receives)
Slice []T Capacity from the first element to the end of the underlying array
Channel chan T Buffer capacity; 0 for unbuffered
nil slice or nil channel 0

Returns: an int.

Usage notes

  • Slicing shifts capacity. s[i:j] has capacity cap(s) - i. A full slice expression s[i:j:k] gives k - i.
  • The growth sequence is not specified. The numbers printed by the second example can differ between Go versions and architectures. Use cap for diagnostics and preallocation, not for logic.
  • Channels. len(ch) is the number of queued elements and cap(ch) the buffer size. Reading them is racy by nature because the state can change immediately; do not use them for synchronization.
  • Preallocation. If you know how many elements you will add, make([]T, 0, n) avoids repeated copying.
  • Arrays. cap(array) is a compile-time constant, like len.
  • Not for strings and maps. cap("abc") or cap(m) is a compile error.
  • Memory retention. A small slice of a huge array keeps the whole array alive. Copy the portion you need if it will outlive the array.