gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:58:17 25 4
gpt4 key购买 nike

我对以下类型转换感到困惑。我希望 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com