2.2 数据类型

peter
• 阅读 1247

基本数据类型

类型
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint64 uintptr
byte // alias for unit8
rune // alias for int32, represents a Unicode code point
float32 float64
complex64 complex128

注意: 默认的 int 型,在 32 位机与 64 位机上所占用的类型分别是 32 和 64,而 int 后面加数字的类型是固定的,便于在不同平台上的兼容性。

类型转换

与其他主要编程语言的差异

  1. Go 语言不允许隐式类型转换
  2. 别名和原有类型也不能进行隐式类型转换

测试示例 1

package type_test

import "testing"

// 测试 Go 对隐式类型转换的约束
func TestImplicit (t *testing.T) {
    var a int = 1
    var b int64
    b = a
    t.Log(a, b)
}

编译错误:cannot use a (type int) as type int64 in assignment

测试示例 2

package type_test

import "testing"

type MyInt int64

// 测试 Go 类型转换
func TestImplicit (t *testing.T) {
    var a int32 = 1
    var b int64
    // 显示类型转换支持
    b = int64(a)
    var c MyInt
    // 即便是别名,也是不允许进行隐式类型转换
    // c = b
    c = MyInt(b)
    t.Log(a, b, c)
}

编译结果:1 1 1

类型预定义值

  1. math.MaxInt64
  2. math.MaxFloat64
  3. math.MaxUint32

可以通过 math 包获取到预定义值

指针类型

与其他主要编程语言的差异

  1. 不支持指针运算
  2. string 是值类型,其默认的初始化值为空字符串,而不是 nil

测试示例 3

// 指针类型
func TestPoint(t *testing.T) {
    a := 1
    aPtr := &a
    t.Log(a, aPtr)  // 输出:1 0xc00001a2a8
    t.Logf("%T %T", a, aPtr) // 输出:int *int
    aPtr = aPtr + 1 // 编译错误:Invalid operation: aPtr + 1 (mismatched types *int and untyped int)
}

测试示例 4

func TestString(t *testing.T) {
    var s string
    t.Log("*" + s + "*") // 输出:**
    t.Log(len(s)) // 输出:0
    if s == "" {
        t.Log("s is empty")
    }
    // 输出:s is empty
}
点赞
收藏
评论区
推荐文章

暂无数据