【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
类型转化
- Go语言不允许隐式类型转换
- 别名和原有类型也不能进行隐式类型转换
不允许隐式类型转换
package type_test
import "testing"
func TestImplicit(t *testing.T) {
var a int = 1
var b int64
b = a
t.Log(a, b)
}
输出
# command-line-arguments_test [command-line-arguments.test]
./type_test.go:10:4: cannot use a (type int) as type int64 in assignment
Compilation finished with exit code 2
修正后:
func TestImplicit(t *testing.T) {
var a int = 1
var b int64
b = int64(a)
t.Log(a, b)
}
输出
=== RUN TestImplicit
--- PASS: TestImplicit (0.00s)
type_test.go:12: 1 1
PASS
Process finished with exit code 0
别名和原有类型也不能进行隐式类型转换
func TestImplicit(t *testing.T) {
var a int = 1
var b int64
b = int64(a)
var c MyInt
c = b
t.Log(a, b, c)
}
输出
# command-line-arguments_test [command-line-arguments.test]
./type_test.go:13:4: cannot use b (type int64) as type MyInt in assignment
Compilation finished with exit code 2
修正后
func TestImplicit(t *testing.T) {
var a int = 1
var b int64
b = int64(a)
var c MyInt
c = MyInt(b)
t.Log(a, b, c)
}
输出
=== RUN TestImplicit
--- PASS: TestImplicit (0.00s)
type_test.go:14: 1 1 1
PASS
Process finished with exit code 0
类型的预定义值
- math.MaxInt64 最大能表示的最大整型
- math.MaxFloat64 最大能表示的浮点型
- math.MaxUint32 最大能表示32位无符号整型
指针类型
- 不支持指针运算
- string是只类型,其默认的初始化值为空字符串,而不是nil
不支持指针运算
func TestPoint(t *testing.T) {
a := 1
aPtr := &a
aPtr = aPtr + 1
t.Log(a, aPtr)
t.Logf("%T %T", a, aPtr)
}
输出
# command-line-arguments_test [command-line-arguments.test]
./type_test.go:20:14: invalid operation: aPtr + 1 (mismatched types *int and int)
Compilation finished with exit code 2
string是只类型,其默认的初始化值为空字符串,而不是nil
func TestString(t *testing.T) {
var s string
t.Log("*"+s+"*")
t.Log(len(s))
if len(s)==0{
t.Log("这是一个空字符串")
}
}
输出
=== RUN TestString
--- PASS: TestString (0.00s)
type_test.go:27: **
type_test.go:28: 0
type_test.go:30: 这是一个空字符串
PASS
Process finished with exit code 0