Go 1.27 reference · Built-in Functions

Go len and cap Function

len returns the number of elements in a string, slice, map, array or channel; cap returns a slice's or channel's capacity.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func len(v Type) int   func cap(v Type) int

Parameters

ParameterDescription
v A string (bytes), slice, array, map or channel.

Examples

Example 1
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	s := make([]int, 2, 5)
	fmt.Println(len(s), cap(s))
	fmt.Println(len("héllo"), utf8.RuneCountInString("héllo"))
	fmt.Println(len(map[string]bool{"a": true}))
}

Output

2 5
6 5
1

Run this on your computer — see “Get Started” for setup.

Nil slices have length 0
package main

import "fmt"

func main() {
	var nilSlice []string
	fmt.Println(len(nilSlice), nilSlice == nil)
	for range nilSlice {
		fmt.Println("never runs")
	}
}

Output

0 true

Run this on your computer — see “Get Started” for setup.

len of a string counts bytes, not characters; use utf8.RuneCountInString for characters.

Was this page helpful?