Go 的接口{}是否与 C 中的 void* 相同? [英] Is Go's interface{} the same as void* in C?

查看:24
本文介绍了Go 的接口{}是否与 C 中的 void* 相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然 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* 相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆