本文由go语言教程栏目给大家介绍go 中 int 的最大数值 ,希望对需要的朋友有所帮助!
总结:
import "math/bits"const (
MaxUint uint = (1 <p><strong>背景:</strong></p><p>我想你知道,<code>uint</code>类型的大小与<code>uint32</code>或<code>uint64</code>相同,具体取决于您所在的平台。通常,只有在没有接近最大值风险的情况下,才会使用无尺寸的版本,因为没有尺寸规格的版本可以使用“本机”类型,这取决于平台,并且它往往更快。</p><p>请注意,更 “快” 是因为使用非本机类型需要处理器执行额外的数学计算和边界检查,以便模拟更大或更小的整数。因此,处理器(或编译器的优化代码)性能会比添加边界检查的代码要好。</p><p>话虽如此,在某些情况下,了解您正在使用的内容仍然很有用。</p><p>“math/bits“ 包中含有以字节为单位的<code>uint</code>大小(译者注:UintSize )。要确定最大值,将 <code>1</code> 左移许多位,再减去 1。即:<code>(1 </code></p><p>请注意,在计算 <code>uint</code> 的最大值时,您通常需要将其显式放入一个 <code>uint</code>(或更大的类型)类型变量中,否则编译器可能会失败,因为它会默认尝试将该计算分配给一个有符号<code>int</code>(很明显,它不适合),所以:</p><pre class="brush:php;toolbar:false;">const MaxUint uint = (1 <p>这是您问题的直接答案,但您可能对一些相关的计算感兴趣。</p><p>根据 spec,<code>uint</code> 和 <code>int</code> 的大小始终相同。</p><blockquote>uint 32 位或 64 位int 与 uint 大小相同</blockquote><p>因此,我们也可以使用这个常量来确定 <code>int</code> 的最大值,方法是采用相同的答案并除以 <code>2</code>,然后减去 <code>1</code>。 即:<code>(1 </code></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig"><img
src="https://img.php.cn/upload/skill/000/000/081/179215391842073.jpg" alt="Golang Uber Dig" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="overflowclass">Golang Uber Dig</a>
<p class="overflowclass">使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等</p>
</div>
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>以及 <code>int</code> 的最小值,通过将 <code>1</code> 移位那么多位并将结果除以 <code>-2</code>。 即:<code>(1 </code></p><p>总之:</p><p>** MaxUint: ** <code>(1 </code></p><p>** MaxInt: ** <code>(1 </code></p><p>** MinInt: ** <code>(1 </code></p><p>完整示例(应与下图相同):</p><pre class="brush:php;toolbar:false;">package mainimport (
"fmt"
"math"
"math/bits"
"runtime"
"strconv")func main() {
var mi32 int64 = math.MinInt32 var mi64 int64 = math.MinInt64 var i32 uint64 = math.MaxInt32 var ui32 uint64 = math.MaxUint32 var i64 uint64 = math.MaxInt64 var ui64 uint64 = math.MaxUint64 var ui uint64 = (1 <p>输出:</p><pre class="brush:php;toolbar:false;">MinInt32: -2147483648
MaxInt32: 2147483647MaxUint32: 4294967295
MinInt64: -9223372036854775808
MaxInt64: 9223372036854775807MaxUint64: 18446744073709551615
MaxUint: 18446744073709551615
MinInt: -9223372036854775808
MaxInt: 9223372036854775807MaxUint: 18446744073709551615MinInt: -9223372036854775808MaxInt: 9223372036854775807系统架构: gc amd64 darwin
Int 大小: 64
原文地址:https://stackoverflow.com/questions/6878...
译文地址:https://learnku.com/go/t/62359










