在我的实际代码中,我使用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