Interface 基于相同接口的混合类型列表
我希望下面的代码可以让我混合类型,并通过它们的接口将它们取回来(也许你可以?),但它显然不起作用。如果不使用反射之类的东西(在大量使用的循环中可能会很昂贵),有没有办法实现我在这里尝试的东西?我是否必须为要存储的每种类型分别列出清单 代码:Interface 基于相同接口的混合类型列表,interface,go,Interface,Go,我希望下面的代码可以让我混合类型,并通过它们的接口将它们取回来(也许你可以?),但它显然不起作用。如果不使用反射之类的东西(在大量使用的循环中可能会很昂贵),有没有办法实现我在这里尝试的东西?我是否必须为要存储的每种类型分别列出清单 代码: package main import ( "fmt" "container/list" ) type Updater interface { Update() } type Cat struct { sound str
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)
错误:
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)
操场:您只需要从第38行的类型断言中删除指针取消引用
如果你改为
v:=e.Value.(更新程序)
,它就会工作。@perreal确实如此。事实上,如果@bojo正确地使用了v
(例如(*v).Update()
),他会得到一个运行时错误,这会让他明白为什么v:=e.Value.(*Updater)
是一个逻辑错误(对编译器来说是不透明的,但在运行时是明显的)。@alphazero,事实上,我就是这样发现它的。在上面的主要评论中,感谢丹尼尔和佩雷尔。