go - 将 int 转换为 uint 时不会出现 panic ?

标签 go

我对以下类型转换感到困惑。我希望 uint 转换为 panic。

a := -1
_ = uint(a) // why no panic?

_ = uint(-1) // panics: constant -1 overflows uint

为什么它不会在第 2 行出现 panic?

https://play.golang.org/p/jcfDL8km2C

最佳答案

issue 6923 中所述:

T(c) where T is a type and c is a constant means to treat c as having type T rather than one of the default types.
It gives an error if c can not be represented in T, except that for float and complex constants we quietly round to T as long as the value is not too large.

这里:

const x uint = -1
var x uint = -1

This doesn't work because -1 cannot be (implicitly) converted to a uint.

_ = uint(a) // why no panic?

因为a不是无类型常量,而是有类型变量(int)。参见 Playground和“what's wrong with Golang constant overflows uint64”:

package main

import "fmt"

func main() {
    a := -1
    _ = uint(a) // why no panic?
    var b uint
    b = uint(a)
    fmt.Println(b)
    // _ = uint(-1) // panics: main.go:7: constant -1 overflows uint
}

结果:4294967295(在 32 位系统上)或 18446744073709551615(在 64 位系统上),如 commented通过 starriet

非常量数值转换的具体规则:

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.

关于go - 将 int 转换为 uint 时不会出现 panic ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918232/

相关文章:

arrays - 在 Golang 中获取指针数组的长度

image - 将多个图像打包成 GOLANG 二进制文件

regex - 如何将子域与 gorilla mux 匹配

file-io - Go - 尝试创建一个 .pgm 文件但最终得到一个二进制文件

go - golang channel 中的函数调用

长数字的 JSON 解码给出 float

scroll - 使用 GXUI 在 Go 中使窗口滚动

go - 如何在本地为模块运行 godoc?

json - 从 Confluence JSON 响应中获取值(value)

go - 嵌入何时使用指针