我对以下类型转换感到困惑。我希望 uint
转换为 panic。
a := -1
_ = uint(a) // why no panic?
_ = uint(-1) // panics: constant -1 overflows uint
为什么它不会在第 2 行出现 panic?
最佳答案
如 issue 6923 中所述:
T(c)
whereT
is a type andc
is a constant means to treatc
as having typeT
rather than one of the default types.
It gives an error ifc
can not be represented inT
, except that forfloat
andcomplex
constants we quietly round toT
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/