Go之旅(五)- 基本类型

原文

tour.golang.org/basics/11

译文

Go的基本类型有:

bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
     // represents a Unicode code point

float32 float64

complex64 complex128
复制代码
package main

import (
	"fmt"// 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
	"math/cmplx"
)

var (
	ToBe   bool       = false
	MaxInt uint64     = 1<<64 - 1
	z      complex128 = cmplx.Sqrt(-5 + 12i)
)

func main() {
	fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
	fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
	fmt.Printf("Type: %T Value: %v\n", z, z)
}
复制代码

译者注

上面的基本数据类型都很常规,其中有个rune感觉有些陌生,看一下官方说明:

// 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
复制代码

文档中很清楚的写到它等价于int32,只是约定在表示字符时用rune来区别整数值。简单来说就是表示整数值时用int32,表示字符时用rune

我们先看一下Go采用的字符集,然后在深入学习rune相关知识。

Go采用Unicode字符集来表示字符,它可以表示65535个字符,也就是说全世界常用的字符不管英文字符,汉字还是日本字都包含在Unicode字符集内。同时,Go默认采用utf-8来编码,utf-8是一种动态编码格式,对于英文来说采用一个字节存储,而对于中文等文字来说采用三个字节。看下例:

package main

import (
	"fmt"
	"math/cmplx"
)

func case2() {
	s := "hello,世界"
	fmt.Println(len(s))
}

func main() {
	case2()
}
复制代码

上面的程序输出多少呢?是8吗(注意,hello后面的是中文逗号)。正确答案是14,因为中文的逗号和世界都占三个字节,所以总共占有5+3*3=14。由此可见len返回的是字符串所占有字节数。

上面我们简单过了一下Go的编码及字符集,现在看一下rune的使用,在讲之前我们先思考一个问题:假如我就想得到上面的字符个数8而不是字节个数14,怎么办?修改一下上面的case2方法如下:

func case2() {
	s := "hello,世界"
	fmt.Println(len(s))
	r := []rune(s)
	fmt.Println(len(r))
}
复制代码

我们通过r:=[]rune(s)s转换为rune数组,这样r中存储的就是每个字符对应的rune值,此时不管每个字符占用多少个字节。然后我们取r的长度就是字符的个数8。

通过上面的程序我们可以看出rune方法可以获得任意字符对应的整数值,也可以通过[]rune获得任意子字符串对应整数数组。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享