基于相同接口的混合类型列表

时间:2012-12-12 04:05:36

标签: interface go

我希望下面的代码允许我混合类型并通过他们的界面取回它们(也许你可以吗?),但它显然不起作用。如果不使用像反射这样的东西,这在一个频繁使用的循环中可能很昂贵,有没有办法实现我在这里尝试的东西?我是否必须为我想要存储的每种类型制作单独的列表?

代码

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_

1 个答案:

答案 0 :(得分:2)

您只需要从第38行的类型断言中删除指针取消引用。

http://play.golang.org/p/SksZhXx3Hp