Go 的接口{}是否与 C 中的 void* 相同?

编程入门 行业动态 更新时间:2024-10-26 17:24:55
本文介绍了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* 相同?

本文发布于:2023-06-04 19:06:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   void

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!