Indexing a slice without enough elements can stop a Go program with an out-of-range panic. The built-in len function gives the size to check before accessing an element. For example, os.Args includes the program name, so a filename at os.Args[1] is available only when len(os.Args) is at least 2. section 2.7.2
What len measures depends on its argument:
- For a slice, it returns the number of elements. Indices start at 0, so the last index is len(slice)-1. section 2.5.4
- For an array, it returns the array's declared number of elements, including elements left at their zero values. section 4.1.2
- For a map, it returns the number of key-value entries. section 4.3.4
- For a string, it returns bytes, not necessarily the number of visible characters. section 3.8.4
Guard an indexed slice
A function that prints three medalists needs at least three contestants. Check `if len(contestants) < 3` and return an error before reading `contestants[0]`, `[1]`, or `[2]`. If any number of contestants is valid, a `range` loop avoids those fixed-index requirements altogether. section 4.2.8
Length also sets loop and slice boundaries. An indexed loop can use `i < len(items)`; `range` supplies indices and stops automatically. In `a[low:high]`, an omitted high bound defaults to `len(a)`. This lets a function use `len(fs)` when averaging a selected slice of measurements. section 4.1.4 section 4.2.6
Check what a string length counts
`len("easy, right?")` is 12, while `len("地鼠")` is 6: the latter has two visible characters represented by six UTF-8 bytes. A loop that indexes the string from 0 to `len(s)-1` visits bytes, which works as expected for ASCII but not for reading individual Unicode characters. section 3.8.4


