既然 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?
推荐答案虽然 C 的 void * 指针和 Go 的 interface{} 变量共享属性,您可以存储任意类型,有一个很大的区别:Go 接口变量也存储了它们所持有的值的类型.
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 运行时可以检查任何类型断言是否正确.
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.
在接口变量中发现的类型信息还允许通过 reflect 包进行复杂的运行时内省,这对于普通的 void * 指针是不可能的.
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.
更多推荐
Go 的接口{}是否与 C 中的 void* 相同?
发布评论