最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Golang中的静态类型和动态类型使用与说明
时间:2026-06-24 08:34:03 编辑:袖梨 来源:一聚教程网
定义说明
- 静态类型(static type):在编码时就能确定的类型,通过变量定义可以确定的类型;
- 动态类型(concrete type):在运行时才能确定具体的数据类型;
动态静态类型如何理解?
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赋值给i,num的实际类型是int, 所以此时,i的动态类型就是int
第五行,把str赋值给i,num的实际类型是string,所以此时,i的动态类型就是string
Golang 中的interface的底层延申
golang 中interface有两种含义/用法:
- 常规的接口类型,有一些带实现的接口定义
- 表示任意数据类型
any
golang 的底层实现也是根据这两种情况做了不同的实现,底层分别对应iface和eface
// 空接口结构
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
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。
您可能感兴趣的文章:- Golang实现读取ZIP压缩包并显示Gin静态html网站
- Golang使用embed引入静态文件的实例代码
- 在Golang中使用http.FileServer返回静态文件的操作
- golang一些常用的静态检查工具详解
相关文章
- 有哪些类似deepseek的软件 06-24
- 腾讯有款三国游戏叫什么 2026流行的腾讯手游排行榜 06-24
- 次元姬小说如何换绑手机号 06-24
- 《虚空之剑术士技能搭配攻略》(发挥虚空之剑的最大威力,成为无敌的剑术士!) 06-24
- centos crontab如何更改任务的执行命令 06-24
- centos crontab 怎样删除已有的任务 06-24