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.
fmt.Println(len("go"), len([]int{1, 2, 3}), len(map[string]int{})) // 2 3 0
Try it
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.
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
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("รฉ")is2because the character is two bytes in UTF-8. Useutf8.RuneCountInString()orlen([]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 bothniland empty slices. Compare withnilonly when the difference matters. - Do not call
lenin every loop condition by habit. It is cheap (the compiler reads a field), sofor 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:
lenis the entry count, not the allocated capacity. There is nocapfor maps. - Not defined for structs, numbers or
nilpointers other than pointer-to-array; those are compile errors.
Related
cap(),make(),string, Slices,utf8.RuneCountInString()- Lessons: Slices, Strings and runes