和其他语言不同,在 Go 语言中没有字符类型,字符只是整数的特殊用例。
为什么说字符只是整数的特殊用例呢?因为在 Go 中,用于表示字符的 byte
和 rune
类型都是整型的别名。在 Go 的源码中我们可以看到:
// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8
// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32
byte
是uint8
的别名,长度为 1 个字节,用于表示 ASCII 字符rune
是int32
的别名,长度为 4 个字节