Menu
Coddy logo textTech

Slice Capacity

Lesson 7 of 21 in Coddy's Slices and Maps in Golang course.

One of the things that may be confusing when dealing with slices is the difference between the length and the capacity. In this lesson, we will dive into understanding what the capacity of a slice is.

Alright, let's get started. This declaration creates a new slice like this one:

var names []string

This is a new slice, so it doesn't have a backing array, and thus, all its fields are zero.

When we use the <strong>len</strong> function or the <strong>cap</strong> function on this slice, both will return 0. However, when I use a slice literal instead, this time Go creates a new backing array:

names := []string{"Python", "Java", "Rust"}

Here, there are three elements in this last literal, so that is why the <strong>names</strong> slice's backing array has three elements as well. Therefore, the capacity is the length of the backing array of a slice, not the length of a slice itself.

To understand this more, let's take another example:

names := []string{"Python", "Golang", "Rust", "JavaScript", "Haskell"}
nameSlice := names[1:]

So, think of this: what will be the capacity of the slice <strong>nameSlice</strong> in this example? 

The answer is 4. Here, we start from index 1 to the end of the slice, and we can check that:

names := []string{"Python", "Golang", "Rust", "JavaScript", "Haskell"}
nameSlice := names[1:]
fmt.Println(nameSlice)
fmt.Println(cap(nameSlice))

The result will be:

[Golang Rust JavaScript Haskell]
4

So remember, to count the capacity, we start from the first position to the end of the slice.

Even if we do something like this:

names := []string{"Python", "Golang", "Rust", "JavaScript", "Haskell"}
nameSlice := names[1:4]
fmt.Println(nameSlice)
fmt.Println(cap(nameSlice))

Here, the length changes, and we only get <strong>three elements</strong>:

[Golang Rust JavaScript]
4

But the capacity still the same. So pay attention to this: the length is not always equal to the capacity."

challenge icon

Challenge

Easy

In the given code, we define a slice of 10 elements. 

  • Perform slicing to create another slice and print its capacity on the screen. It should be equal to 6.

Try it yourself

package main

import (
	"fmt"
)

func main() {
    // Slice of 10 Elements
	lang := []string{"Python", "Java", "JavaScript", "C++", "Go", "Ruby", "Swift", "Rust", "PHP", "Kotlin"}
	// Do Sicing Here
 
	// Complete the Print function 
	fmt.Println("the capacity of this Slice is :" ?)

}

All lessons in Slices and Maps in Golang