×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Slice Length and Capacity

Last Updated : May 05, 2025

In Go, every slice has a length and a capacity.

The length of a slice is the number of elements it currently contains.

The capacity is the number of elements the slice can hold before it needs to allocate more memory.

Getting Length and Capacity

You can use the built-in functions len() and cap() to get the length and capacity of a slice.

Example

In this example, we are printing the length and capacity of a slice of Indian cities:

package main
import "fmt"

func main() {
    cities := []string{"Delhi", "Mumbai", "Kolkata"}
    
    fmt.Println("Cities:", cities)
    fmt.Println("Length:", len(cities))
    fmt.Println("Capacity:", cap(cities))
}

When executed, this program outputs:

Cities: [Delhi Mumbai Kolkata]
Length: 3
Capacity: 3

Slicing and Capacity

When you create a new slice from an existing one, its length and capacity can differ. The capacity of the new slice depends on the original slice's backing array.

Example

In this example, we create a new slice from a larger slice and observe its length and capacity:

package main
import "fmt"

func main() {
    states := []string{"Punjab", "Haryana", "Kerala", "Gujarat", "Odisha"}
    southStates := states[2:4] // ["Kerala", "Gujarat"]

    fmt.Println("South states:", southStates)
    fmt.Println("Length:", len(southStates))
    fmt.Println("Capacity:", cap(southStates))
}

When executed, this program outputs:

South states: [Kerala Gujarat]
Length: 2
Capacity: 3

Length and Capacity after Append

When you append elements to a slice, the length increases. If the new length exceeds the capacity, Go automatically allocates a new array with more capacity.

Example

In this example, we append a student's name to the slice and observe the change in length and capacity:

package main
import "fmt"

func main() {
    students := []string{"Ravi", "Priya"}
    fmt.Println("Before append - Length:", len(students), "Capacity:", cap(students))

    students = append(students, "Ayesha")
    fmt.Println("After append - Length:", len(students), "Capacity:", cap(students))
}

When executed, this program outputs something like:

Before append - Length: 2 Capacity: 2
After append - Length: 3 Capacity: 4

Exercise

Select the correct option to complete each statement about slice length and capacity in Go.

  1. The function to get the length of a slice s in Go is ___.
  2. The function to get the capacity of a slice s in Go is ___.
  3. If a slice is created as s := make([]int, 3, 5), then len(s) returns ___ and cap(s) returns ___.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.