I see all sorts of Kind enums in Go's reflect
package. But no byte
.
Why is that? There is a definite distinction made between the other numeric types. Why not byte
? Are we supposed to assume uint8
instead?
Yes, byte
is an alias for uint8
: "all numeric types are distinct except byte
, which is an alias for uint8
, and rune
, which is an alias for int32
" (italics mine). You can even write code like var x []uint8 = []byte("hi!")
and it compiles.
Since there's no difference except in how the source is written, the reflect
package can't do much special with byte
s when manipulating the (identical) structures in RAM at runtime.
Thinking more about Kind
s specifically, they refer to data storage rather than type names. So, for example, if you declare type A uint8
, variables of types A
and uint8
will have distinct reflect.Type
s but the same Kind
:
package main
import (
"fmt"
"reflect"
)
type A uint8
func main() {
x, y := A(1), uint8(1)
valX, valY := reflect.ValueOf(x), reflect.ValueOf(y)
fmt.Println("Types: x is", valX.Type(), "y is", valY.Type())
fmt.Println("Types match:", valX.Type() == valY.Type())
fmt.Println("Kinds: x is", valX.Kind(), "y is", valY.Kind())
fmt.Println("Kinds match:", valX.Kind() == valY.Kind())
}
has output
Types: x is main.A y is uint8
Types match: false
Kinds: x is uint8 y is uint8
Kinds match: true
So though it's a little silly to think about hypothetical languages, even if Go byte
were a distinct type rather than an alias, they'd have the same reflect.Kind
.
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