1
我希望下面的代码可以让我混合类型并通过它们的接口将它们取回(也许你可以?),但它显然不起作用。如果没有使用像反射这样的东西,这在使用频繁的循环中可能很昂贵,有没有办法实现我在这里尝试的?我将不得不为每个我想存储的类型制作单独的列表?基于相同接口的混合类型列表
代码:
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 undefined (type *Updater has no field or method Update)
游乐场:http://play.golang.org/p/lN-gjogvr_
它的作品,如果你做'v:= e.Value。(更新)'代替。 – perreal
@perreal。事实上,如果@bojo正确地使用了'v'(例如'(* v).Update()'),他会得到一个运行时错误,这会让他直观地理解为什么'v:= e.Value。(* Updater )'是一个逻辑错误(对编译器来说是不透明的,但是在运行时会显示)。 – alphazero
@alphazero,其实这也是我发现它的方法 – perreal