“接口{}”的作用是什么? Go 中的语法?
我已经通读了 effective Go 和 Go 教程以及一些源代码,但是 Go 语法背后的确切机制对我来说有些神秘。我第一次看到它是在尝试实现 heap.Interface 时,它似乎是某种容器(有点让我想起了 monad),我可以从中提取任意类型的值。
为什么 Go 编写为使用这个?这是泛型的某种解决方法吗?有没有一种更优雅的方法从 heap.Interface
获取值,而不是使用 heap.Pop(&h).(*Foo)
(在堆指针指向 Foo 类型的情况)?
I've read through the Effective Go and Go Tutorials as well as some source, but the exact mechanism behind the interface {}
syntax is Go is somewhat mysterious to me. I first saw it when trying to implement heap.Interface
and it seems to be a container of some kind (reminds me of a monad a little) from which I can extract values of arbitrary type.
Why is Go written to use this? Is it some kind of workaround for generics? Is there a more elegant way to get values from a heap.Interface
than having to dereference them with heap.Pop(&h).(*Foo)
(in the case of a heap pointers to type Foo)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
interface{}
是一个可以容纳所有东西的通用盒子。 go中的接口定义了一组方法,任何实现这些方法的类型都符合接口。interface{}
没有定义任何方法,因此根据定义,每个类型都符合此接口,因此可以保存在interface{}
类型的值中。它根本不像泛型。相反,它是一种放松类型系统并表示“任何值都可以在此处传递”的方法。 C 中此功能的等效项是
void *
指针,但在 Go 中您可以查询所保存值的类型。interface{}
is a generic box that can hold everything. Interfaces in go define a set of methods, and any type which implements these methods conforms to the interface.interface{}
defines no methods, and so by definition, every single type conforms to this interface and therefore can be held in a value of typeinterface{}
.It's not really like generics at all. Instead, it's a way to relax the type system and say "any value at all can be passed here". The equivalent in C for this functionality is a
void *
pointer, except in Go you can query the type of the value that's being held.这是一篇出色的博客文章,解释了正在发生的事情在引擎盖下。
Here is an excellent blog post that explains what is going on under the hood.