在Go语言中,”interface {}”语法的作用是什么?

huangapple go评论92阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2011年2月9日 06:46:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/4939398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定