doulan7166 2011-02-08 22:46
浏览 149
已采纳

Go中“ interface {}”语法的作用是什么?

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)?

  • 写回答

2条回答 默认 最新

  • douyan1972 2011-02-08 23:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教