Go语言如何在内置类型(如map和slice)中实现泛型?

huangapple go评论64阅读模式
英文:

How does go implement Generic in built-in type like map and slice?

问题

我们知道,我们可以声明各种类型的映射和切片,比如[]string, []int, []interface{}。这已经是一种泛型了。

我想知道它是如何实现的?
它是否就像interface{}一样,存储typevalue,就像在C语言中使用void*来实现泛型一样?

英文:

As we know, we can declare all type of map and slice,like []string, []int, []interface{}
This is already some kind of Generic.

I wonder how it implements?
Is it just like interface{}, storing type and value, like using void* to implement Generic in c language?

答案1

得分: 1

在Gopher Academy的YouTube频道上找到了相关的解释,Keith Randall解释了关于映射(maps)以及如何实现它以支持多种类型而不使用泛型的内容。

视频链接 - Keith Randall - 映射实现内部原理

正如描述的那样,并且你可以在src/runtime/type.go中看到,类型信息由_type处理。

type _type struct {
	size       uintptr
	ptrdata    uintptr // 存储所有指针的内存前缀的大小
	hash       uint32
	tflag      tflag
	align      uint8
	fieldAlign uint8
	kind       uint8
	// 用于比较此类型对象的函数
	// (指向对象A的指针,指向对象B的指针) -> ==?
	equal func(unsafe.Pointer, unsafe.Pointer) bool
	// gcdata 存储垃圾收集器的GC类型数据。
	// 如果 kind 中设置了 KindGCProg 位,则 gcdata 是一个GC程序。
	// 否则它是一个 ptrmask 位图。有关详细信息,请参见 mbitmap.go。
	gcdata    *byte
	str       nameOff
	ptrToThis typeOff
}

*_type 用于描述Go中的映射(maps)、切片(slices)、数组(arrays)和通道(channels)中的键和元素类型。

参考:maptypeslicetype

英文:

Found related explanation in Gopher Academy youtube channel, Keith Randall explaining about maps and how it is implemented to have many types without generics.

video link - Keith Randall - Inside the Map Implementation

As it is described and you can see in src/runtime/type.go Type informations are handled by this _type.

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 is using to describe key and element types in go maps, slices, arrays, channels.

ref := maptype, slicetype

huangapple
  • 本文由 发表于 2021年8月15日 21:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68791873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定