Is it possible to have a struct in go that can also be accessed as a slice? So, for example, I'd want something like this:
type Item struct {
Name string
}
type ItemList struct {
PackDate time.Time
[]Item
}
And then I could access an Item in the ItemList as a slice.
myItemList[0].Name
Or access the members of ItemList in the normal struct way.
myItemList.PackDate
If this is not possible, are there any recommended patterns for handling a sort of slice with metadata like this in go?
The recommended thing to do is to simply access the slice as a struct field:
type Item struct {
Name string
}
type ItemList struct {
PackDate time.Time
Items []Item
}
Accessing the values:
myItemList.Items[0].Name
myItemList.PackDate
Iterating over the slice:
for _, item := range myItemList.Items {
// do something with item.Name
}
For example,
package main
import (
"fmt"
"time"
)
type Item struct {
Name string
}
type ItemList struct {
PackDate time.Time
Items []Item
}
func main() {
list := ItemList{
PackDate: time.Now(),
Items: []Item{{Name: "John"}, {Name: "Jane"}},
}
fmt.Println(list)
fmt.Println(list.PackDate)
fmt.Println(list.Items[1].Name)
}
Output:
{2009-11-10 23:00:00 +0000 UTC [{John} {Jane}]}
2009-11-10 23:00:00 +0000 UTC
Jane