Go的interface{}和C语言中的void*是一样的吗?

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

Is Go's interface{} the same as void* in C?

问题

由于interface{}类型的变量可以具有任何值,这是否意味着它本质上类似于C语言中的void*一样的通用指针?

英文:

Since a variable of type interface{} can have any value, does that mean it is essentially a general pointer like a void* in C?

答案1

得分: 22

C语言的void *指针和Go语言的interface{}变量都具有存储任意类型的特性,但有一个重要的区别:Go语言的接口变量还会存储所持有值的类型信息。

因此,C程序员需要确保从void *指针到特定类型的任何强制类型转换都是安全的,而Go运行时可以检查任何类型断言是否正确。

接口变量中的类型信息还允许通过reflect包进行复杂的运行时反射,而这在普通的void *指针中是不可能的。

英文:

While C's void * pointers and Go's interface{} variables share the property that you can store arbitrary types, there is one big difference: Go interface variables also store the type of the value they hold.

So while a C programmer is expected to make sure that any casts from void * pointers to specific types are safe, the Go runtime can check that any type assertions are correct.

The type information found in interface variables also allows for sophisticated runtime introspection through the reflect package, which would be impossible with a plain void * pointer.

答案2

得分: 6

我倾向于说“完全不是!”。但我承认它可能达到与“容纳任何东西”相同的目的。

  1. interface {} 不是一个指针,所以你不能对其进行解引用操作。
  2. 你可以将 void* 强制转换为任何类型,但对 interface {} 进行类型断言可能会导致运行时恐慌。
  3. 对于 void* 指向的实际类型的确定是复杂的(或不可能的),但是 reflect 包允许你对 interface {} 进行这样的操作。

所以,interface {} 是空接口,与 C 语言中的 void* 没有任何关系,只是有一个小例外,即它们都可以用于处理你不关心其真实性质的任何东西。

英文:

I am inclined to say "Not at all!". But I admit that it may server the same purpose of "holding whatever comes along".

  1. An interface {} is not a pointer so you cannot dereference it.
  2. You can cast a void* to anything but type asserting an interface {} might result in a runtime panic.
  3. It is complicated (or impossible) to determine the actual type a void* points to but package reflect lets you do this for interface {}.

So no! interface {} is the empty interface and has nothing to do with a void* in C with the small exception that both might be used to handle anything where you do not care about the real nature of it.

答案3

得分: 0

不,如果涉及的接口类型是空的,即没有方法,那么itable除了保存指向原始类型的指针之外没有任何作用。在这种情况下,可以丢弃itable,直接将值指向类型。

英文:

No, if the interface type involved is empty—it has no methods—then the itable serves no purpose except to hold the pointer to the original type. In this case, the itable can be dropped and the value can point at the type directly.
REF:
https://research.swtch.com/interfaces

huangapple
  • 本文由 发表于 2013年11月19日 16:32:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/20066637.html
匿名

发表评论

匿名网友

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

确定