Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang中的静态类型和动态类型

Golang中的静态类型和动态类型使用及说明

作者:YPLee_8

这段描述主要解释了静态类型和动态类型的概念,并通过Golang中的interface变量举例说明了这两种类型的区别,文章详细解析了在不同赋值操作下,变量的静态类型和动态类型的变化过程,强调了interface在Golang中的特殊作用

定义说明

动态静态类型如何理解?

go 语言中interface(any)可以承接所有类型的数据,所以这部分只有具体运行的时候,才能确定数据具体类型:

	var i interface{}
	var num int = 1
	var str string = "hello world"
	i = num
	i= str

在该示例中,第一行声明了一个interface的变量i,在编码时就可以确定了,所以i的静态类型就是interface;

同理,第二行num的静态类型为int,第三行str的静态类型为string

第四行,把num赋值给inum的实际类型是int, 所以此时,i的动态类型就是int

第五行,把str赋值给inum的实际类型是string,所以此时,i的动态类型就是string

Golang 中的interface的底层延申

golang 中interface有两种含义/用法:

  1. 常规的接口类型,有一些带实现的接口定义
  2. 表示任意数据类型any

golang 的底层实现也是根据这两种情况做了不同的实现,底层分别对应ifaceeface

// 空接口结构
type eface struct {
    _type *_type			// 实体类型
    data  unsafe.Pointer	// 数据地址
}

// 包含方法的结构
type iface struct {
    tab  *itab			// 接口和实体类型
    data unsafe.Pointer	// 数据地址
}

type itab struct {
    inter *interfacetype
    _type *_type
    hash  uint32 // copy of _type.hash. Used for type switches.
    _     [4]byte
    fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}

type interfacetype struct {
    typ     _type
    pkgpath name
    mhdr    []imethod
}

type imethod struct {
   name nameOff
   ityp typeOff
}

type _type struct {
    size       uintptr
    ptrdata    uintptr // size of memory prefix holding all pointers
    hash       uint32
    tflag      tflag
    align      uint8
    fieldAlign uint8
    kind       uint8
    // function for comparing objects of this type
    // (ptr to object A, ptr to object B) -> ==?
    equal func(unsafe.Pointer, unsafe.Pointer) bool
    // gcdata stores the GC type data for the garbage collector.
    // If the KindGCProg bit is set in kind, gcdata is a GC program.
    // Otherwise it is a ptrmask bitmap. See mbitmap.go for details.
    gcdata    *byte
    str       nameOff
    ptrToThis typeOff
}

type nameOff int32
type typeOff int32
type tflag uint8

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文