为什么反射包中没有"字节"类型?

cho*_*wey 4 reflection types go

我看到各种各样的种类在围棋的枚举reflect包.但没有byte.

这是为什么?其他数字类型之间存在明确的区别.为什么不byte呢?我们应该假设uint8吗?

two*_*two 9

是的,byte是别名uint8:"所有数字类型都是不同的,除了 byte,它是别名uint8,并且rune,它是int32"(italics mine)的别名.你甚至可以编写代码,var x []uint8 = []byte("hi!") 并将其编译.

由于除了如何编写源代码之外没有区别,因此在运行时在RAM中操作(相同)结构时,reflect封装对bytes 不起作用.

更多地考虑Kinds,他们指的是数据存储而不是类型名称.因此,举例来说,如果你声明type A uint8的类型变量Auint8 将有明显reflect.Type秒,但相同的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())
}
Run Code Online (Sandbox Code Playgroud)

有输出

Types: x is main.A y is uint8
Types match: false
Kinds: x is uint8 y is uint8
Kinds match: true
Run Code Online (Sandbox Code Playgroud)

因此,虽然考虑假设语言有点傻,但即使Go byte是一个独特的类型而不是别名,它们也有相同的含义reflect.Kind.