liveBook · Manning

Len()

As explained in Go in Action, Second Edition

len is a Go built-in function that returns the number of bytes in a string or the number of elements in a supported collection.

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

How Go in Action, Second Edition covers it

How deep it goes
Defines length for collections and strings, works through panic prevention and UTF-8 byte counts, but defers detailed encoding mechanics.
Examples
Uses a three-medalist slice that can panic and a two-character Unicode string whose length is six bytes.
What it assumes
Assumes basic Go indexing and loop syntax while introducing len as a built-in function.
What you can do after
Diagnose/debug with it to prevent out-of-range access and distinguish UTF-8 byte counts from visible character counts.
How it connects
Connects len to slice indexing, range loops, slice expressions, and UTF-8 encoding.

Also explained in

Compare how 3 books explain len() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.