我希望下面的代碼允許我混合類型并通過它們的接口取回它們(也許可以嗎?),但是顯然不起作用。如果不使用像反射這樣的東西(在頻繁使用的循環(huán)中可能會很昂貴),有沒有辦法實現(xiàn)我在這里嘗試的東西?我是否需要為要存儲的每種類型分別列出清單?代碼:package mainimport ( "fmt" "container/list")type Updater interface { Update()}type Cat struct { sound string}func (c *Cat) Update() { fmt.Printf("Cat: %s\n", c.sound)}type Dog struct { sound string}func (d *Dog) Update() { fmt.Printf("Dog: %s\n", 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() }}錯誤:prog.go:38: v.Update undefined (type *Updater has no field or method Update)游樂場:http://play.golang.org/p/lN-gjogvr_
- 1 回答
- 0 關(guān)注
- 219 瀏覽
添加回答
舉報
0/150
提交
取消