英文:
How does go implement Generic in built-in type like map and slice?
问题
我们知道,我们可以声明各种类型的映射和切片,比如[]string, []int, []interface{}
。这已经是一种泛型了。
我想知道它是如何实现的?
它是否就像interface{}
一样,存储type
和value
,就像在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)中的键和元素类型。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论