=========加法运算结果不符合预期=========

FreeWong · · 2297 次点击
```go func add[signed ~int | ~int8 | ~int16 | ~int32 | ~int64](x, y signed) signed { s := x + y if (x^s)&(y^s) < 0 { // (+) + (+) = (-) || (-) + (-) = (+) panic("signed overflow") } return s } func subtract[signed ~int | ~int8 | ~int16 | ~int32 | ~int64](x, y signed) signed { d := x - y if (x^y)&(x^d) < 0 { // (+) - (-) = (-) || (-) - (+) = (+) panic("signed overflow") } return d } ```
#10
更多评论
```go 1111 1111 + 1111 1111 ─────────────── 1 1111 1110 后8字节 1111 1110 = 254 ```
#1
<a href="/user/zzustu" title="@zzustu">@zzustu</a> 感谢,知道将高位字节丢弃了,我的问题就是为什么要丢失 , 难道在 golang 中 uint8 + uint8=uint8 ?
#2