32 go
rune
Go中的类型定义为
别名,
int32
并且int32
在所有方面都等同于.按照惯例,它用于区分字符值和整数值.
如果目的是使用这种类型的代表字符值,为什么Go语言的作者没有使用uint32
,而不是int32
?rune
当它是负数时,他们如何期望在程序中处理一个值?另一个类似的类型byte
是uint8
(而不是int8
)的别名,这似乎是合理的.
che*_*eng 18
我用谷歌搜索并找到了这个:https://groups.google.com/forum/#!topic / golang -nuts/d3_GPK8bwBg
这已被问过好几次了.符文占用4个字节而不仅仅是一个,因为它应该存储unicode代码点而不仅仅是ASCII字符.与数组索引类似,数据类型已签名,因此您可以在对这些类型进行算术运算时轻松检测溢出或其他错误.
它不会\xe2\x80\x99t 变为负值。目前 Unicode 中有 1,114,112 个代码点,0x7fffffff
即使考虑到所有保留块,也远远低于 2,147,483,647 ( ) \xe2\x80\x93 。
最近的 Unicode 6.3 定义了超过 110,000 个符号。这需要每个代码点至少有 21 位表示,因此符文就像 int32 并且具有大量位。
但关于溢出或负值问题,请注意一些 unicode 函数(如unicode.IsGraphic)的实现包括:
我们转换为
uint32
以避免额外的阴性测试
代码:
const MaxLatin1 = '\u00FF' // maximum Latin-1 value.
// IsGraphic reports whether the rune is defined as a Graphic by Unicode.
// Such characters include letters, marks, numbers, punctuation, symbols, and
// spaces, from categories L, M, N, P, S, Zs.
func IsGraphic(r rune) bool {
// We convert to uint32 to avoid the extra test for negative,
// and in the index we convert to uint8 to avoid the range check.
if uint32(r) <= MaxLatin1 {
return properties[uint8(r)]&pg != 0
}
return In(r, GraphicRanges...)
}
Run Code Online (Sandbox Code Playgroud)
这可能是因为符文应该是常量(如“ Go符文类型解释”中提到的,其中符文可以是int32
oruint32
或 Evenfloat32
或 ...:它的常量值授权它存储在任何这些数字中类型)。
归档时间: |
|
查看次数: |
4734 次 |
最近记录: |