在我的實際代碼中,我使用encoding/xml
來解析XML文檔,而且我基本上有一堆嵌套結構,其形式爲—,所有這些可能會多次出現,除了頂級statements
元素:對項目集合執行操作
statements
statement
opcode
args
pre
post
我是相當新的去吧,我清楚地誤解interface{}
(空接口)是如何工作的:
.\stmtgen.go:58: cannot use print_name (type func(Statement)) as type func(interface {}) in argument to performAction
.\stmtgen.go:58: cannot use slist (type []Statement) as type []interface {} in argument to performAction
相關的例子代碼:
package main
import "fmt"
// Actually a structure in my code, but this suffices for demonstration.
type Opcode int
// A Statement has a Name and multiple Opcodes may use this Name.
type Statement struct {
Name string
Opcodes []Opcode
}
// Print the statement name.
func print_name(stmt Statement) {
fmt.Println(stmt.Name)
}
// Perform an action on each item of a collection.
func performAction(action func(interface{}), v []interface{}) {
for i := range v {
action(v[i])
}
}
func main() {
slist := make([]Statement, 3)
slist[0] = Statement{"Statement 1"}
slist[1] = Statement{"Statement 2"}
slist[2] = Statement{"Statement 3"}
//ERROR HERE
performAction(print_name, slist)
}
我必須創建函數來打印每種類型的值嗎?
戈拉ng不會隱式地將'[] Statement'轉換爲'[] interface {}',因爲這是昂貴的,並且隱藏昂貴的語法流程很糟糕,您必須將每個'Statement'轉換爲'interface {} for循環前傳遞給performAction(...) – nevernew