您的位置 首页 golang

详解golang的数据类型和底层实现四

今天来看看golang剩下的其他数据类型。golang早期是用c实现的编译器,后来的版本用自举重写来编译器,go被称为类c语言,有些数据类型底层和c的数据类型保持一致,有些做了struct封装。

interface{}空接口类型,前边有一篇文章讲过interface是定义一组方法合集,但是空接口比较特殊,底层的实现也不一样,由类型指针和具体底层数据指针组成。

 type eface struct { // 16 bytes
    _type *_type   //指向底层类型
    data  unsafe.Pointer //指向底层数据(具体值)
}  

空接口变量可以指向任何类型数据,.(type)在switch可以判断底层数据类型,.(tring)可以断言获取底层数据的值

 func main() {
var a interface{}
a = "hello"
change(a)
b, ok :=a.(string)
fmt.Println(b, ok)
}

func change(a interface{})  {
a = "world"
}  

整数类型int8、uint8、int16、uint16、int32、uint32、int64、uint64,浮点类型float32、float64,指针类型uintptr和intptr是无符号和有符号指针(存放地址,64位占8字节,32位4字节)是基础类型。byte类是unit8的别名,rune类型是int32的别名用于表示unicode字符

 // 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  

string类型底层是一个byte数组实现的,len是字符串长度,str指向byte数组存放字符的值,所以和数组一样是不可变的,range遍历就是遍历的底层byte数组

 type stringStruct struct {
str unsafe.Pointer
len int
}  

bool布尔类型,true and false.

 // bool is the set of boolean values, true and false.
type bool bool

// true and false are the two untyped boolean values.
const (
true  = 0 == 0 // Untyped bool.
false = 0 != 0 // Untyped bool.
)  

golang有定义类型别名和再定义类型两种方式,两种方式是有区别的,不能定义非本地类型的方法

 类型再定义:

type A int32
类型别名:

type A = int32  
 func main() {
var a intgo = 10
fmt.Println(a.val())
var b stringgo = "hello world"
fmt.Println(b.val())
}

type intgo int
type stringgo = string

func (i intgo) val() int {
return int(i)
}
func (i stringgo) val() string {
return string(i)
}  

文章来源:智云一二三科技

文章标题:详解golang的数据类型和底层实现四

文章地址:https://www.zhihuclub.com/86913.shtml

关于作者: 智云科技

热门文章

网站地图