0
0
Goprogramming~5 mins

Slice length and capacity in Go

Choose your learning style9 modes available
Introduction

Slices in Go let you work with parts of arrays easily. Knowing their length and capacity helps you manage how much data they hold and how much space they can grow into.

When you want to know how many items are currently in a slice.
When you want to check how much more you can add to a slice without making a new array.
When you want to avoid unexpected slowdowns by pre-allocating enough space.
When you want to understand how slicing affects the underlying array.
When debugging or optimizing memory use in your program.
Syntax
Go
len(slice)  // returns the number of elements in the slice
cap(slice)  // returns the capacity of the slice (size of underlying array from start of slice)

len(slice) gives how many elements are currently in the slice.

cap(slice) shows how many elements the slice can hold before needing a new array.

Examples
This slice has 5 elements and capacity 5 because it uses the whole array.
Go
s := []int{1, 2, 3, 4, 5}
fmt.Println(len(s))  // 5
fmt.Println(cap(s))  // 5
The new slice s2 has length 2 (elements 2 and 3) but capacity 4 because it can grow up to the end of the original array.
Go
s := []int{1, 2, 3, 4, 5}
s2 := s[1:3]
fmt.Println(len(s2))  // 2
fmt.Println(cap(s2))  // 4
This slice is created with length 3 but capacity 10, so it has space to add more elements without resizing.
Go
s := make([]int, 3, 10)
fmt.Println(len(s))  // 3
fmt.Println(cap(s))  // 10
Sample Program

This program shows the length and capacity of an original slice, a slice made from it, and a new slice created with make. It helps see how length and capacity change.

Go
package main

import "fmt"

func main() {
    s := []int{10, 20, 30, 40, 50}
    fmt.Printf("Original slice: %v\n", s)
    fmt.Printf("Length: %d, Capacity: %d\n", len(s), cap(s))

    s2 := s[1:4]
    fmt.Printf("Sliced slice: %v\n", s2)
    fmt.Printf("Length: %d, Capacity: %d\n", len(s2), cap(s2))

    s3 := make([]int, 2, 5)
    fmt.Printf("New slice with make: %v\n", s3)
    fmt.Printf("Length: %d, Capacity: %d\n", len(s3), cap(s3))
}
OutputSuccess
Important Notes

Length is how many elements you can use right now.

Capacity is how many elements you can add before Go needs to create a new bigger array.

Slicing a slice can reduce length but capacity depends on how much space is left in the original array.

Summary

Length tells how many items are in the slice.

Capacity tells how many items the slice can hold before growing.

Understanding length and capacity helps you write efficient Go programs.