2012-12-12 36 views
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_

+2

它的作品,如果你做'v:= e.Value。(更新)'代替。 – perreal

+2

@perreal。事實上,如果@bojo正確地使用了'v'(例如'(* v).Update()'),他會得到一個運行時錯誤,這會讓他直觀地理解爲什麼'v:= e.Value。(* Updater )'是一個邏輯錯誤(對編譯器來說是不透明的,但是在運行時會顯示)。 – alphazero

+1

@alphazero,其實這也是我發現它的方法 – perreal

回答

相關問題