Go语言支持的数据类型
Go语言内置了如下基本类型:
- 布尔bool (不能接受其他类型的赋值,不支持自动或者强制的类型转换)
- 整形int8,byte,int16,int,int64,uint,uintptr等(int和int32会认为是不同的类型,不能直接比较,编译器不会做强转)
- 浮点float32,float64(float32相当于C语言的float,float64相当于double)
- 复数complex64,complex128 (value = 3.2 + 12i)
- 字符串string (Go 语言仅支持UTF-8和Unicode)
- 字符rune
- 错误error
此外,还有一些复合类型
- 指针
- 数组
- 切片
- 字典
- 通道
- 结构体
- 接口
类型转换
数值和字符串
对于int64类型我们需要strconv.ParseInt,对于string我们需要string(),对于bool我们需要strconv.ParseBool
// 数字(int)->字符串
str1 := strconv.Itoa(i)
// 数字(int64)->字符串
str2 := fmt.Sprintf("%d", i)
// 字符串->数字(int)
id, err := strconv.Atoi(id)
// 字符串->数字(int64)
id, _ := strconv.ParseInt("100", 10, 64)
字符串和[]byte
// 字符串转byte数组
str := "Hello"
bytes := []byte(str)
// []byte转字符串
str := string(bytes)
使用断言
通过断言将接口转换为已知类型
v, ok := y.(I)
I表示类型,这里是断言y为I类型,如果成功ok为true,v将是I类型的值。
使用反射
使用Reflection在运行时获取对象类型
var x = 2013
switch reflect.ValueOf(x).Kind() {
case reflect.Int:
fmt.Println("It's an int!")
case reflect.String:
fmt.Println("It's a string!")
}
