Uint and uintptr in golang

huangapple go评论80阅读模式
英文:

Uint and uintptr in golang

问题

我知道在Go语言中,uintptr的大小规则与uint相同;
我猜测uintuintptr是相同的,只是在使用情况上有所不同。那么为什么在Go的内置类型中,uintptr不是uint的别名,就像byteuint8的别名,runeint32的别名一样呢?

英文:

I know uintptr follow same rules for its size with uint in Go;
I guess uint and uintptr are the same and only they are different in the use case. so why uintptr is not an alias for uint in go built-ins like how byte is an alias for uint8 and rune for int32?

答案1

得分: 3

根据Go的规范,以下是对于"无大小限制"整数数据类型的定义:

  • uint:可以是32位或64位
  • int:与uint具有相同的大小
  • uintptr:一个足够大以存储指针值的未解释位的无符号整数

可以看到,这两种类型都有一个独特的大小定义。即使它们在大多数平台上巧合地具有相同的大小,但没有语言级别的理由将这些类型混淆。

还有一个使用指针整数的独特类型的好处:由于Go具有严格的类型检查,你不能将uintptr直接用作其他int类型,需要先进行转换。这很重要,因为在Go中,uintptr主要用于unsafe操作,因此具有独特的类型可以在可能误用不安全特性时提供强烈的指示或错误提示(或者至少会让你三思而后行)。

英文:

From the Go spec, here is how the sizes of the "unsized" integer data types are defined:

> uint either 32 or 64 bits
>
> int same size as uint
>
> uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value

As you can see, both types have a distinct size definition. Even if they are coincidentally the same size on most (?) platforms, there's no language-level reason why these types should be conflated.

There's also the benefit of having a distinct type for pointer integers: as Go has strict typing, you cannot use a uintptr as any other int type without converting it first. This is important because uintptr is primarily used for unsafe purposes in Go, so having a distinct type gives strong indications or errors when you might be misusing unsafe features (or at least, it will make you think twice about it).

huangapple
  • 本文由 发表于 2021年9月15日 01:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/69182402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定