Menu
Coddy logo textTech

Slice Length vs Capacity

Part of the Fundamentals section of Coddy's GO journey — lesson 77 of 109.

In Go, length and capacity are two different properties of slices.

Create a slice with make:

numbers := make([]int, 3, 5)
fmt.Println("Length:", len(numbers))
fmt.Println("Capacity:", cap(numbers))

This displays:

Length: 3
Capacity: 5

Length is the number of elements currently in the slice. Capacity is the maximum number of elements the slice can hold before needing to grow.

challenge icon

Challenge

Beginner
In this challenge, you'll explore the difference between a slice's len() and cap() functions. The len() function returns the current number of elements in a slice, while cap() returns the capacity (maximum number of elements before reallocation is needed).

Your task is to complete the code to print both the length and capacity of the given slice.

Cheat sheet

In Go, slices have two properties: length and capacity.

Length is the number of elements currently in the slice. Capacity is the maximum number of elements the slice can hold before needing to grow.

Use len() to get the length and cap() to get the capacity:

numbers := make([]int, 3, 5)
fmt.Println("Length:", len(numbers))    // Length: 3
fmt.Println("Capacity:", cap(numbers))  // Capacity: 5

Try it yourself

package main

import "fmt"

func main() {
	// A slice with 3 elements but capacity of 5
	numbers := make([]int, 3, 5)
	
	// TODO: Print the length of the slice using len()
	fmt.Println("Length:", ?)
	
	// TODO: Print the capacity of the slice using cap()
	fmt.Println("Capacity:", ?)
	
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals