遇到一个关于类型转换的奇怪的

willre · · 860 次点击
首先,是因为你这个是个常量 代码调整一下 ``` func main() { const x = uint64(256) fmt.Println(byte(x)) } ``` 就报一样的错了。 然后,这种事肯定要查spec https://golang.org/ref/spec#Variables 带符号的整数转换在spec的 Conversions between numeric types 很明确的写着 For the conversion of non-constant numeric values, the following rules apply: When converting between integer types, if the value is a signed integer, it is sign extended to implicit infinite precision; otherwise it is zero extended. It is then truncated to fit in the result type's size. For example, if v := uint16(0x10F0), then uint32(int8(v)) == 0xFFFFFFF0. The conversion always yields a valid value; there is no indication of overflow. 带符号的规则转换只对非常量数字有效 然后常量呢? 向下拉 Constant expressions 找到1楼回答的那个句子 "The values of typed constants must always be accurately representable by values of the constant type. The following constant expressions are illegal: " 下面第一个无效的例子 ``` uint(-1) // -1 cannot be represented as a uint ``` 和你这个一模一样 所以,这就是语法的定义。
#3
更多评论
官方说法 A constant value x can be converted to type T if x is representable by a value of T. 详见 https://blog.csdn.net/qq_30895047/article/details/103829227
#1
但这句话还是没解决我的疑问 通过x := uint64(256) 中 x的值是超过byte的表示范围的,确可以正常执行 直接用byte转换uint64(256) 就报错, 报错的原因怀疑是因为 直接用uint64(256)时,uint64(256)表示的是一个常量 您的blog里写的太底层了,我看不懂
#2