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.
s := make([]int, 2, 10) fmt.Println(len(s), cap(s)) // 2 10
Try it
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.
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
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 capacitycap(s) - i. A full slice expressions[i:j:k]givesk - i. - The growth sequence is not specified. The numbers printed by the second example can differ between Go versions and architectures. Use
capfor diagnostics and preallocation, not for logic. - Channels.
len(ch)is the number of queued elements andcap(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, likelen. - Not for strings and maps.
cap("abc")orcap(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.
Related
len(),append(),make(),copy(), Slices, Channels- Lessons: Slice internals, Slices, Buffered channels and select