len
The built-in Go function that returns how many items a string, slice, map, array or channel holds.
In more detail
len of a nil slice or nil map is 0, so you can check emptiness without a nil check. For a string it counts bytes, not characters. Checking len(os.Args) before indexing avoids an index-out-of-range panic.
Example
if len(args) < 2 { os.Exit(2) }Related terms
- slice — A flexible, growable view over a list of values of one type, written like []string, and Go's everyday list.
- map — A Go collection that stores values by key, such as service name to port number, and looks them up quickly.
- os.Args — The slice of strings holding the words a Go program was started with, where os.Args[0] is the program itself.
Taught in
- Variables, Typing, and Zero Values — Concurrent Systems Programming with Go
- Arrays, Slices, and Maps — Concurrent Systems Programming with Go
- Panics and Recover — Concurrent Systems Programming with Go
- Files and the os Package — Concurrent Systems Programming with Go
- Parsing Arguments with flag — Concurrent Systems Programming with Go