在给定示例的 unit8 和 int8 数据类型的算术运算中得到负数和零结果的原因是什么
package main
import (
"fmt"
)
func main() {
var u uint8 = 255
fmt.Println(u, u+1, u*u) // "255 0 1"
var i int8 = 127
fmt.Println(i, i+1, i*i) // "127 -128 1"
}
最佳答案
Go 不会在运行时因整数溢出而 panic 。根据 doc :
For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".
For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. No exception is raised as a result of overflow. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.
关于go - uint8, int8 的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605650/