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

huangapple go评论84阅读模式
英文:

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.

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

huangapple
  • 本文由 发表于 2012年12月12日 12:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/13832596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定