首页 > 解决方案 > 为什么 Golang 像这样在 atoi.go 中处理截止?

问题描述

// code in atoi.go, line 90
var cutoff uint64
switch base {
case 10:
    cutoff = maxUint64/10 + 1
case 16:
    cutoff = maxUint64/16 + 1
default:
    cutoff = maxUint64/uint64(base) + 1
}

我在 Golang 包的 atoi.go 文件中看到了一些代码,为什么不像下面这样写呢?

var cutoff = maxUint64/uint64(base) + 1

非常感谢。

标签: gooverflowatoi

解决方案


我认为您所指的行上方的评论可能会回答您的问题:

// 对常见情况使用编译时常量。

因为只有引用常量maxUint64/10 + 1maxUint64/16 + 1编译器才能计算出来。结果是每次ParseUint调用都不需要在运行时进行除法运算。您可以在commit中查看基准。


推荐阅读