gpt4 book ai didi

go - Golang int到uint8收敛,未检测到溢出

转载 作者:行者123 更新时间:2023-12-01 22:10:38 25 4
gpt4 key购买 nike

我一直在做“A Go of Go”,并且在Pic函数中发生了一些奇怪的行为。它涉及 int-> uint8 转换。程序执行时,默认情况下, dx dy 的值为 256 。这样嵌套for循环中的 x + y 会上升到 510 ! (255 + 255)

不过,Golang在将溢出的 x + y 转换为uint8时没有发现任何问题,但是当我将其更改为某个硬编码值时,可以说uint8(321),我立即获得溢出错误。

有人可以向我解释这种奇怪的行为吗?

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
canvas := make([][]uint8, dy)

for y := 0; y < dy; y++ {
canvas[y] = make([]uint8, dx)
for x := 0; x < dx; x++ {
canvas[y][x] = uint8(x+y) // <- here it is
}
}

return canvas;
}

func main() {
pic.Show(Pic)
}
获得错误:
go: finding module for package golang.org/x/tour/pic
go: downloading golang.org/x/tour v0.0.0-20200508155540-0608babe047d
go: found golang.org/x/tour/pic in golang.org/x/tour v0.0.0-20200508155540-0608babe047d
./prog.go:11:24: constant 321 overflows uint8

Go build failed.

最佳答案

这是从语言规范中得出的:

类型化常量的值必须始终可以由常量类型的值准确表示。以下常量表达式是非法的:
uint(-1)// -1不能表示为一个单位
int(3.14)// 3.14不能表示为int

在您的情况下,xyint,因此x+y也是int,而uint8(x+y)只是截断结果。但是,根据语言规范uint8(321)无效。但是,这是有效的:

i:=321
x:=uint8(i)

关于go - Golang int到uint8收敛,未检测到溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63947309/

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