Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does len() returned a signed value?

Tags:

signed

go

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)
like image 428
daxelrod Avatar asked Aug 22 '16 21:08

daxelrod


1 Answers

len() (and cap()) return int because that is what is used to index slices and arrays (not uint). So the question is more "Why does Go use signed integers to index slices/arrays when there are no negative indices?".

The answer is simple: It is common to compute an index and such computations tend to underflow much too easy if done in unsigned integers. Some innocent code like i := a-b+7 might yield i == 4294967291 for innocent values for aand b of 6 and 10. Such an index will probably overflow your slice. Lots of index calculations happen around 0 and are tricky to get right using unsigned integers and these bugs hide behind mathematically totally sensible and sound formulas. This is neither safe nor convenient.

This is a tradeoff based on experience: Underflow tends to happen often for index calculations done with unsigned ints while overflow is much less common if signed integers are used for index calculations.

Additionally: There is basically zero benefit from using unsigned integers in these cases.

like image 73
Volker Avatar answered Sep 19 '22 17:09

Volker