Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go len() function

Reference for Go len(): the length of strings (in bytes), arrays, slices, maps and channels, constant results, nil values and the byte versus rune trap.

len() returns how many elements a value holds. It works on strings, arrays, pointers to arrays, slices, maps and channels, and always returns an int. It is a built-in, so it needs no import.

What counts as "one element" depends on the type. For a string it is a byte, not a character, which surprises people the first time they measure non-English text. For a channel it is the number of values currently waiting in the buffer.

Go
fmt.Println(len("go"), len([]int{1, 2, 3}), len(map[string]int{}))
// 2 3 0

Try it

Go len() on every kind of value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func len(v Type) int
Type of v Result
string Number of bytes
[n]T or *[n]T n
[]T Number of elements (0 for nil)
map[K]V Number of entries (0 for nil)
chan T Number of queued values (0 for nil)

Returns: an int. Since Go 1.18 len also accepts a type parameter whose type set only contains types that len supports.

Edge cases: len of a nil slice, map or channel is 0 and does not panic. If v is a constant string, or an array (or pointer to array) whose expression has no channel receives or function calls, len(v) is a compile-time constant.

Usage notes

  • Strings count bytes. len("รฉ") is 2 because the character is two bytes in UTF-8. Use utf8.RuneCountInString() or len([]rune(s)) for characters. Even runes are not always what a person sees as one letter (accented letters built from several code points).
  • Empty checks: write len(s) == 0, which is true for both nil and empty slices. Compare with nil only when the difference matters.
  • Do not call len in every loop condition by habit. It is cheap (the compiler reads a field), so for i := 0; i < len(s); i++ is fine.
  • Channels: the value is a snapshot; other goroutines may change it right after you read it, so never base synchronization on it.
  • Maps: len is the entry count, not the allocated capacity. There is no cap for maps.
  • Not defined for structs, numbers or nil pointers other than pointer-to-array; those are compile errors.