简体   繁体   English

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

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

由于interface{}类型的变量可以具有任何值,这是否意味着它本质上是一个通用指针,如 C 中的 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.虽然 C 的void *指针和 Go 的interface{}变量共享可以存储任意类型的属性,但有一个很大的区别:Go 接口变量也存储它们所持有的值的类型。

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.因此,尽管 C 程序员应确保从void *指针到特定类型的任何强制转换都是安全的,但 Go 运行时可以检查任何类型断言是否正确。

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.在接口变量中找到的类型信息还允许通过reflect包进行复杂的运行时自省,这对于普通的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. interface {}不是指针,因此您不能取消引用它。
  2. You can cast a void* to anything but type asserting an interface {} might result in a runtime panic.您可以将void*强制转换为任何内容,但类型断言interface {}可能会导致运行时恐慌。
  3. It is complicated (or impossible) to determine the actual type a void* points to but package reflect lets you do this for interface {} .确定void*指向的实际类型很复杂(或不可能),但包 reflect 允许您为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. interface {}是空接口,与 C 中的void*无关,但两者都可能用于处理您不关心其真实性质的任何事情。

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.不,如果涉及的接口类型是空的——它没有方法——那么 itable 除了保存指向原始类型的指针之外没有其他用途。 In this case, the itable can be dropped and the value can point at the type directly.在这种情况下,可以删除 itable 并且值可以直接指向类型。 REF: https://research.swtch.com/interfaces参考: https ://research.swtch.com/interfaces

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM