英文:
What is the role of the "interface {}" syntax in Go?
问题
我已经阅读了《Effective Go》和Go教程以及一些源代码,但是interface {}
语法背后的确切机制对我来说有些神秘。我第一次看到它是在尝试实现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)?
答案1
得分: 7
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 type interface{}
.
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.
答案2
得分: 1
这是一篇很好的博客文章,解释了引擎内部发生的事情。
英文:
Here is an excellent <a href="http://research.swtch.com/2009/12/go-data-structures-interfaces.html">blog post</a> that explains what is going on under the hood.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论