当前位置: 首页 > news >正文

Golang 中的静态类型和动态类型

定义说明

  • 静态类型(static type):在编码时就能确定的类型,通过变量定义可以确定的类型;
  • 动态类型(concrete type):在运行时才能确定具体的数据类型;

动态静态类型如何理解?

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

	var i interface{}var num int = 1var str string = "hello world"i = numi= 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 *_typehash  uint32 // copy of _type.hash. Used for type switches._     [4]bytefun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}type interfacetype struct {typ     _typepkgpath namemhdr    []imethod
}type imethod struct {name nameOffityp typeOff
}type _type struct {size       uintptrptrdata    uintptr // size of memory prefix holding all pointershash       uint32tflag      tflagalign      uint8fieldAlign uint8kind       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    *bytestr       nameOffptrToThis typeOff
}type nameOff int32
type typeOff int32
type tflag uint8
http://www.lryc.cn/news/160897.html

相关文章:

  • docker的数据卷、docker数据持久化
  • 阅读源码工具Sourcetrail
  • KMP 算法详解
  • [matconvnet]matconvnet-1.0-beta-25在cuda11.1以上编译问题总结
  • 自动化驱动程序管理
  • 智能合约编写高级篇(二)区块哈希介绍
  • 二进制链表转整数
  • Python爬虫进阶:使用Scrapy库进行数据提取和处理
  • 五)Stable Diffussion使用教程:文生图之高清修复
  • SQL SERVER 如何实现UNDO REDO 和PostgreSQL 有近亲关系吗
  • SpringBoot原理-自动配置-原理分析-源码跟踪
  • 安全基础 --- 原型链污染
  • c++中的常用知识点总结
  • Leetcode:349. 两个数组的交集【题解超详细】
  • Java 【异常】
  • B - Polycarp‘s Practice
  • 朴素贝叶斯数据分类------
  • flask中的操作数据库的插件Flask-SQLAlchemy
  • arrow的使用
  • 【24种设计模式】装饰器模式(Decorator Pattern(Wrapper))
  • 小程序v-for与key值使用
  • Qt包含文件不存在问题解决 QNetworkAccessManager
  • 【视频图像篇】FastStone Capture屏幕长截图软件
  • 【C语言】每日一题(杨氏矩阵查找数)
  • 探究SpringWeb对于请求的处理过程
  • 如何使用Google Compute Engine入门指南快速创建和配置您的云虚拟机实例
  • springMVC中全局异常处理
  • 【Nginx24】Nginx学习:压缩模块Gzip
  • 我的私人笔记(zookeeper分布式安装)
  • 小程序排名优化全攻略