【问题标题】:"does not support indexing" : providing indexing with an interface?“不支持索引”:通过接口提供索引?
【发布时间】:2016-10-06 16:02:47
【问题描述】:

https://play.golang.org/p/qxhocI6mjY

在这部剧中,我得到了这个错误:invalid operation: s[0] (type AlmostSlice does not support indexing) 所以我想知道,是否可以实现索引?

给定这样的结构:

type AlmostSlice struct {
    Entities []string
    Id       string
    Stuffs   string
}

是否可以让它支持索引?

s := AlmostSlice{Id: "bar", Entities: []string{"foo"}}
... := s[0]
s[0] = "stuffs"

例如,通过实现这样的东西:

func (s *AlmostSlice) Index(i int) string {
    return s.Entities[i]
}

【问题讨论】:

  • 没有。来自spec:索引表达式表示“数组的元素、指向数组、切片、字符串或映射的指针”

标签: go


【解决方案1】:

好问题。在其他语言中,您可以实现一些神奇的接口来做类似的事情,但在 Go 中,关键是我们没有这些东西。所以要回答你的问题,从 1.7 开始,你不能在结构上实现索引。

【讨论】:

    【解决方案2】:

    你不能。 Go 的目标是简单并按照它的指示去做,而不是调用底层方法。如果它支持索引,那么它是一个切片/数组、一个字符串或一个映射。所以你可以做this,虽然它可能不是你想要的。

    出于这个原因,我建议您简单地按照您在问题中的建议进行操作,即使用一种从实体中选择元素的方法:

    func (s AlmostSlice) Get(i int) string {
        return s.Entities[i]
    }
    

    也就是说,据我所知,目前最好的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 2022-11-27
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 2012-12-04
      • 2014-04-23
      相关资源
      最近更新 更多