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:
0 <= len(s) <= cap(s)
"len()
" (Again, hard to see how a sequence could have a negative number of bytes)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 a
and 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With