我想做这样的事情,但显然不可能以这种方式进行,我认为我想念一些东西。
type command struct {
help string
handler func (params ...interface{})
}
func showHelp( commands map[string]command ) {
fmt.Println( "Help:" )
for c, h := range commands {
fmt.Println( c,"->" ,h.help )
}
}
func main() {
// Map to store commands
commands := make( map[string]command )
// Adding help command
commands["help"] = command{ "show this information", showHelp }
}
最佳答案
你有一个类型不匹配,因为你的结构成员需要一个 func(param ...interface) 而你正试图传递一个 func(map[string]command)
参见 here有关接口(interface)类型如何工作的解释。
如果您如下更改代码并为结构成员提供简单的类型接口(interface){},它可以采用任何类型,包括我认为是您想要的函数。
package main
import "fmt"
type command struct {
help string
handler interface{}
}
func showHelp(commands map[string]command) {
fmt.Println("Help:")
for c, h := range commands {
fmt.Println(c, "->", h.help)
}
}
func main() {
// Map to store commands
commands := make(map[string]command)
// Adding help command
commands["help"] = command{"show this information", showHelp}
showHelp(commands)
}
关于go - 存储通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655299/