英文:
Uint and uintptr in golang
问题
我知道在Go语言中,uintptr
的大小规则与uint
相同;
我猜测uint
和uintptr
是相同的,只是在使用情况上有所不同。那么为什么在Go的内置类型中,uintptr
不是uint
的别名,就像byte
是uint8
的别名,rune
是int32
的别名一样呢?
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论