Go's builtin len()
function returns a signed int
. Why wasn't a uint
used instead?
Is it ever possible for len()
to return something negative?
As far as I can tell, the answer is no:
- Arrays: "The number of elements is called the length and is never negative."
- Slices: "At any time the following relationship holds:
0 <= len(s) <= cap(s)
" - Maps "The number of map elements is called its length". (I couldn't find anything in the spec that explicitly restricts this to a nonnegative value, but it's difficult for me to understand how there could be fewer than 0 elements in a map)
- Strings "A string value is a (possibly empty) sequence of bytes.... The length of a string s (its size in bytes) can be discovered using the built-in function
len()
" (Again, hard to see how a sequence could have a negative number of bytes) - Channels "number of elements queued in channel buffer (ditto)