Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no "byte" kind in the reflect package?

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?

like image 956
chowey Avatar asked Jun 12 '16 01:06

chowey


1 Answers

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 bytes when manipulating the (identical) structures in RAM at runtime.

Thinking more about Kinds 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.Types 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.

like image 129
twotwotwo Avatar answered Oct 06 '22 00:10

twotwotwo