2016-06-12 36 views

回答

8

是,byte is an alias for uint8:“所有数值类型是不同的除了byte,其是用于uint8的别名,rune,这是一个别名int32”(斜体矿)。您甚至可以编写代码,如var x []uint8 = []byte("hi!")and it compiles

由于除了编写源代码之外没有区别,reflect程序包在运行时在RAM中操作(相同)结构时不能做很多特殊的操作。

多想想Kind小号具体而言,它们是指数据存储而非类型名称。因此,举例来说,如果你声明type A uint8,和类型A变量uint8will 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()) 
} 

具有输出

Types: x is main.A y is uint8 
Types match: false 
Kinds: x is uint8 y is uint8 
Kinds match: true 

所以,虽然这是一个有点傻去想假设语言,即使转到byte是一个独特的类型而不是别名,他们有相同的reflect.Kind

+0

很酷,我没有意识到它被语言规范定义为别名。 (为什么符文是'int32'而不是'uint32',呵呵?) – chowey

+0

很难说!字节必须是无符号的,因为所有的值都是有效的,并且约定它们是0-255。对于Unicode代码点,他们有一个选择,因为不超过2^31个代码点。我认为他们更喜欢在某些地方签名ints(比如数组索引),因为unsigned wraparound('0-1 == 0xffffffff')可能不直观。另一方面,位移量被定义为uint! (也许这是因为试图进行负面转变可能会以与架构相关的方式发生奇怪的行为,而不仅仅是因为惯例而失效。) – twotwotwo

相关问题