How can I pass in Golang a function as an argument that can have potentially multiple arguments, e.g. fmt.Printf
?
The first problem is that one has to define the type of the function to be passed first.
type FunctionWithVariableArgumentLength func(s string, object1 type1, ..., objectn typen)
The second problem is that one does not know what types the arguments in the list may have, like in fmt.Printf
.
There's a prototype as for other functions : http://golang.org/pkg/fmt/#Printf
So you can define your function accepting a function as argument like this :
func exe(f func(string, ...interface{}) (int, error)) {
f("test %d", 23)
}
func main() {
exe(fmt.Printf)
}
You would use a similar signature as the one for fmt.Printf
func yourFunction(a ...interface{})
To answer the 1st part: writing functions with a variable number of arguments.
// sums returns the total of a variable number of arguments
func sum(numbers ...int) total int {
total = 0
for _, n := range numbers {
total += n
}
return total
}
The 2nd Part is harder but the function definition looks like:
func doVarArgs(fmt string, a ...interface{}) {
The variable a
contains a slice of values of the type interface{}
. You then iterate over the slice pulling each argument and using the package "reflect" to query the type of each argument.
See http://golang.org/pkg/reflect/ for a full explanation.