I would like to do something like this, but apparently it is not possible in this way, I think that there is something I miss.
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 }
}
You have a type mismatch in that your struct member expects an func(param ...interface) and you are trying to pass it a func(map[string]command)
See here for the explanation on how interface types work.
If you change your code as below and give the struct member simply type interface{} it can take any type including a function which I think is what you want.
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)
}
Try in on the Go Playground
I think you're looking for something like this;
package main
import "fmt"
type command struct {
help string
handler func()
}
func main() {
c := command{}
c.handler = func () {
fmt.Println("Hello, playground")
}
c.handler()
}
At least this is how I would do it. Put a field of type func on your struct then in whatever place is convenient use a closure to assign a method to it.
You will need type assertion in your handlers - cost of generics. Your design as is, non-idiomatic but can work just as proof_of_concept.
package main
import "fmt"
type command struct {
help string
handler func(params ...interface{})
}
func showHelp(commands ...interface{}) {
fmt.Println("Help:")
for c, h := range commands[0].(map[string]command) { //type assertion here
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}
commands["help"].handler(commands)
}