Go is a statically typed language, if you would call a function or method by name, the compiler could not check if the parameters you provide match the signature of the function.
Instead use function variables: your variable that currently holds the method or function name can be be a variable of function type, holding a function or method value.
Let's assume we have the following logging functions:
func Info(args ...interface{}) {
fmt.Print("[Info] ")
fmt.Println(args...)
}
func Error(args ...interface{}) {
fmt.Print("[Error] ")
fmt.Println(args...)
}
You may use it like this:
var logger func(...interface{}) = Info
func main() {
logger("something")
logger = Error
logger("Some other thing")
}
Output will be (try it on the Go Playground):
[Info] something
[Error] Some other thing
Also note that this works with methods too, not just with functions:
type Logger struct{}
func (l Logger) Info(args ...interface{}) {
fmt.Print("[Info] ")
fmt.Println(args...)
}
func (l Logger) Error(args ...interface{}) {
fmt.Print("[Error] ")
fmt.Println(args...)
}
Using it:
var mainLogger = Logger{}
var logger func(...interface{}) = mainLogger.Info
func main() {
logger("something")
logger = mainLogger.Error
logger("Some other thing")
}
Output (try it on the Go Playground):
[Info] something
[Error] Some other thing
See related question: golang function alias on method receiver