There are some similar designs in the go interface. For example, the results of reading and writing can only be values >= 0
. Why not just use the unsigned int
type? What is the purpose of using signed types?
// The Copy function uses ReaderFrom if available.
type ReaderFrom interface {
ReadFrom(r Reader) (n int64, err error)
}
// The Copy function uses WriterTo if available.
type WriterTo interface {
WriteTo(w Writer) (n int64, err error)
}
I found a good explanation in the book Go Programming Language (A. Donovan, B. Kernighan):
Although Go provides unsigned numbers and arithmetic, we tend to use the signed
int
form even for quantities that can’t be negative, such as the length of an array, thoughuint
might seem a more obvious choice. Indeed, the built-inlen
function returns a signedint
, as in this loop which announces prize medals in reverse order:
medals := []string{"gold", "silver", "bronze"}
for i := len(medals) - 1; i >= 0; i-- {
fmt.Println(medals[i]) // "bronze", "silver", "gold"
}
The alternative would be calamitous. If
len
returned an unsigned number, theni
too would be auint
, and the conditioni >= 0
would always be true by definition. After the third iteration, in whichi == 0
, thei--
statement would causei
to become not −1, but the maximumuint
value, and the evaluation ofmedals[i]
would fail at run time, or panic, by attempting to access an element outside the bounds of the slice. For this reason, unsigned numbers tend to be used only when their bitwise operators or peculiar arithmetic operators are required, as when implementing bit sets, parsing binary file.
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