go - uint8, int8 的算术运算

标签 go int

在给定示例的 unit8int8 数据类型的算术运算中得到负数和零结果的原因是什么

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"
}

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

最佳答案

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/

相关文章:

android - Windows 上适用于 Android 的 Golang?

c - 在 32 位机器上对一些小值使用 __int8_t 是无用的优化工作吗?

c - scanf 和 printf 中的无效 int

android - 为什么 android.content.ContentResolver.delete 返回一个整数?

go - 在 Go 中解析多个模板

docker - 使用 gRPC 进行容器间通信

http - Golang CSRF 在结构中保存模板字段

java - 从字符串中提取数字并转换为 2 位小数

string - 如何在Go中将整数转换为固定长度的十六进制字符串?

go - K8s运算符(operator)监听具体配置图