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]
}
Good question. In other languages there are magic interfaces you can implement to do stuff like that but in Go the point is we don't have those things. So to answer your question, no as of 1.7 you can't implement indexing on a struct.
You can't. Go aims to be simple and to do what it's told to, not to call underlying methods. If it supports indexing, then it's a slice/array, a string or a map. So you could do this, although it's probably not what you want.
For this reason, I would recommend you to simply do what you've suggested in your question, which is to have a method that picks an element from the Entities:
func (s AlmostSlice) Get(i int) string {
return s.Entities[i]
}
That is, as far as I know, the best way to go currently.