Is there an equivalent in golang to check if a function exists in a package/ go file like it is done in python.
mymethod in dir(package)
Is there an equivalent in golang to check if a function exists in a package/ go file like it is done in python.
mymethod in dir(package)
It looks like from this post that it is not directly possible.
You could always create your own package to search package files and check if the method exists, as explained in the above post's first answer.
Based on your comments, it sounds like you may simply use a map the contains available functions. Here's a complete example:
package main
import (
"flag"
"fmt"
"os"
)
func main() {
var option string
var data string
flag.StringVar(&option, "option", "default", "The option to choose from")
flag.StringVar(&data, "data", "", "The data to use")
flag.Parse()
options := map[string]func(string) string{
"foo": func(data string) string {
fmt.Println("do something with data using option foo")
return data
},
"bar": func(data string) string {
fmt.Println("do something with data using option bar")
return data
},
"default": func(data string) string {
fmt.Println("do something with data using default option")
return data
},
}
method, found := options[option]
if !found {
fmt.Println("option is not available")
os.Exit(1)
}
result := method(data)
fmt.Println(result)
}
Output
$ go run main.go -data hello -option foo
do something with data using option foo
hello
$ go run main.go -data hello -option whatever
option is not available
$ go run main.go -data hello
do something with data using default option
hello