I was hoping the following code would allow me to mix types and fetch them back by their interface (maybe you can?), but it clearly does not work. Without using something like reflection, which might be expensive in a heavily used loop, is there a way to achieve what I am trying here? Am I going to have to make separate lists for each type I want to store?
Code:
package main
import (
"fmt"
"container/list"
)
type Updater interface {
Update()
}
type Cat struct {
sound string
}
func (c *Cat) Update() {
fmt.Printf("Cat: %s
", c.sound)
}
type Dog struct {
sound string
}
func (d *Dog) Update() {
fmt.Printf("Dog: %s
", d.sound)
}
func main() {
l := new(list.List)
c := &Cat{sound: "Meow"}
d := &Dog{sound: "Woof"}
l.PushBack(c)
l.PushBack(d)
for e := l.Front(); e != nil; e = e.Next() {
v := e.Value.(*Updater)
v.Update()
}
}
Error:
prog.go:38: v.Update undefined (type *Updater has no field or method Update)
Playground: http://play.golang.org/p/lN-gjogvr_