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
intform even for quantities that can’t be negative, such as the length of an array, thoughuintmight seem a more obvious choice. Indeed, the built-inlenfunction 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
lenreturned an unsigned number, thenitoo would be auint, and the conditioni >= 0would always be true by definition. After the third iteration, in whichi == 0, thei--statement would causeito become not −1, but the maximumuintvalue, 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