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
Syntax
func len(v Type) int func cap(v Type) int
Parameters
| Parameter | Description |
|---|---|
v |
A string (bytes), slice, array, map or channel. |
Examples
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.
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.
Related
append· Add elements to the end of a slice, growing its backing array when needed; always assign the result back.make· Create and initialise a slice, map or channel, optionally with a length and capacity (slices) or buffer size (channels).- Go Strings · tutorial