英文:
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
我倾向于说“完全不是!”。但我承认它可能达到与“容纳任何东西”相同的目的。
interface {}
不是一个指针,所以你不能对其进行解引用操作。- 你可以将
void*
强制转换为任何类型,但对interface {}
进行类型断言可能会导致运行时恐慌。 - 对于
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".
- An
interface {}
is not a pointer so you cannot dereference it. - You can cast a
void*
to anything but type asserting aninterface {}
might result in a runtime panic. - It is complicated (or impossible) to determine the actual type a
void*
points to but package reflect lets you do this forinterface {}
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论