How []interface{} in Go is implemented?

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

How []interface{} in Go is implemented?

问题

在Go语言中,可以这样做:

func main() {
	var intSlice []interface{}
	intSlice = append(intSlice, "hello world")
	intSlice = append(intSlice, 1)
	for _, v := range intSlice {
		fmt.Println(v)   // hello world
                         // 1
	}
}

由于切片底层是一个数组,在没有给定特定类型的情况下,Go如何知道该数组的内存结构?如果是[]string,那么我知道在每次迭代时,我必须将当前地址加上4以获取下一个项的地址,但对于interface{},Go如何知道该做什么?我感到困惑。对于这个问题可能的解释是interface{}实际上是一个指针,所以[]interface{}只存储指针,值1或"hello world"存储在切片之外的某个地方。关于这一点,我是正确的吗?

英文:

In Go I can do something like this:

func main() {
	var intSlice []interface{}
	intSlice = append(intSlice, "hello world")
	intSlice = append(intSlice, 1)
	for _, v := range intSlice {
		fmt.Println(v)   // hello world
                         // 1
	}
}

Since a slice is deep down an array, without given a specific type to that array, how can Go know the layout of this array's memory structure? If it's a []string then I know that for every iteration I have to add current address with 4 to get the next item's address, but for an interface{} how can Go knows what to do? I am confused. One possible explain for this is that interface{} is actually a pointer, so []interface{} stores pointers only, the value 1 or "hello world" is stored somewhere outside of the slice. Am I right about this?

答案1

得分: 1

一个接口包含两个值:一个指向值的指针,和一个指向值类型的指针。所以一个包含所有int值的[]interface{}实际上是一个接口数组,其中每个元素包含这两个值,数组的每个元素指向int值和它的类型。

英文:

An interface is two values: a pointer to the value, and a pointer to the type of the value. So a []interface{} containing all int values is simply an array of interfaces, where each element containing those two values, with each element of the array pointing to the int value, and to its type.

huangapple
  • 本文由 发表于 2021年12月11日 09:59:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/70312094.html
匿名

发表评论

匿名网友

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

确定