douhoujun9304
2016-10-06 16:02
浏览 38
已采纳

“不支持索引”:为接口提供索引吗?

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

In this play, I get this error : invalid operation: s[0] (type AlmostSlice does not support indexing) So I am wondering, is it possible to implement indexing ?

Given a struct like this :

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

Is it possible to make it support indexing ?

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

For example, by implementing something like this :

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

图片转代码服务由CSDN问答提供 功能建议

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

在此播放中,我收到此错误:无效的操作:s [0](类型 AlmostSlice不支持索引)</ code> 所以我想知道是否可以实现索引?</ p>

给出这样的结构:</ p>

  type AlmostSlice struct {
实体[] string 
 ID字符串
 Stuffs字符串
} 
 </ code> </ pre> 
 
 

是否可以使其支持索引 ?</ p>

  s:= AlmostSlice {Id:“ bar”,实体:[] string {“ foo”}} 
 ...:= s [0] 
s  [0] =“东西” 
 </ code> </ pre> 
 
 

例如,通过实现以下内容:</ p>

  func(s  * AlmostSlice)索引(i int)字符串{
返回s.Entities [i] 
} 
 </ code> </ pre> 
 </ div>

2条回答 默认 最新

相关推荐 更多相似问题