interface - 基于相同接口(interface)的混合类型列表

标签 interface go

我希望下面的代码允许我混合类型并通过它们的接口(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 undefined (type *Updater has no field or method Update)

Playground :http://play.golang.org/p/lN-gjogvr_

最佳答案

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

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

关于interface - 基于相同接口(interface)的混合类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832596/

相关文章:

c# - C# 中的接口(interface)是否可能出现菱形问题?

Golang gorilla mux 未找到处理程序无法正常工作

go - 如何用golang实现slowEqual

design-patterns - Java 默认接口(interface)方法具体用例

go - 使用接口(interface)为任意类型创建队列

go - 为什么我的 for 循环不能正确循环元素?

go - 在新包中使用标志值

pointers - golang 中的指针

android - 在 Kotlin 中实例化接口(interface)监听器

java - 转换为未实现的接口(interface)编译