英文:
List of mixed types based on same interface
问题
我希望以下代码可以让我混合类型并通过它们的接口获取它们(也许你可以?),但显然它不起作用。在不使用像反射这样可能在频繁使用的循环中昂贵的东西的情况下,有没有办法实现我在这里尝试的目标?我是否需要为每种类型创建单独的列表来存储?
代码:
package main
import (
"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未定义(类型*Updater没有Update字段或方法)
Playground: http://play.golang.org/p/lN-gjogvr_
英文:
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\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()
}
}
Error:
prog.go:38: v.Update undefined (type *Updater has no field or method Update)
Playground: http://play.golang.org/p/lN-gjogvr_
答案1
得分: 2
你只需要从第38行的类型断言中移除指针解引用。
英文:
You just need to remove the pointer dereference from the type assertion on line 38.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论