dongshi3605 2016-06-12 01:47
浏览 32

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

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?

  • 写回答

1条回答 默认 最新

  • douqiju2520 2016-06-12 02:01
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路