0
0
GoHow-ToBeginner · 3 min read

How to Find Capacity of Slice in Go: Simple Guide

In Go, you can find the capacity of a slice using the built-in cap() function. This function returns the total number of elements the slice can hold without allocating more memory.
📐

Syntax

The syntax to find the capacity of a slice is simple:

  • cap(slice): Returns the capacity of the given slice.

The slice is the variable holding your slice data.

go
capacity := cap(slice)
💻

Example

This example shows how to create a slice and find its capacity using cap(). It prints the length and capacity of the slice.

go
package main

import "fmt"

func main() {
    numbers := make([]int, 3, 5) // length 3, capacity 5
    fmt.Println("Slice:", numbers)
    fmt.Println("Length:", len(numbers))
    fmt.Println("Capacity:", cap(numbers))
}
Output
Slice: [0 0 0] Length: 3 Capacity: 5
⚠️

Common Pitfalls

Some common mistakes when working with slice capacity:

  • Confusing len() with cap(). len() gives the number of elements currently in the slice, while cap() gives the total space allocated.
  • Assuming capacity changes automatically when appending. Capacity only grows when needed, not on every append.
  • Using cap() on arrays returns the array length, which might be confusing.
go
package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    fmt.Println("Length:", len(s))   // 3
    fmt.Println("Capacity:", cap(s)) // 3

    s = append(s, 4)
    fmt.Println("After append - Length:", len(s))   // 4
    fmt.Println("After append - Capacity:", cap(s)) // Capacity may increase
}
Output
Length: 3 Capacity: 3 After append - Length: 4 After append - Capacity: 6
📊

Quick Reference

Remember these quick tips when working with slice capacity in Go:

  • cap(slice) returns the total allocated space.
  • len(slice) returns the current number of elements.
  • Capacity can be larger than length.
  • Appending beyond capacity increases capacity automatically.

Key Takeaways

Use the built-in cap() function to get a slice's capacity in Go.
Capacity shows how many elements the slice can hold without resizing.
Length and capacity are different; length is current size, capacity is total space.
Appending to a slice may increase its capacity automatically.
Always check capacity when optimizing memory or performance.