Is there a golang way to get a function's runtime arguments?
I'm asking because I'm trying to write a function that takes a function and a string, and then outputs the string and the runtime arguments.
Is there a golang way to get a function's runtime arguments?
I'm asking because I'm trying to write a function that takes a function and a string, and then outputs the string and the runtime arguments.
Unlike JavaScript where a function can be called with extra arguments not included in the declaration, calls to Go functions must match the function signature. So there isn't a need for the special arguments
global.
With that said, it is possible to write variadic functions that can take a variable number of arguments. For example, the following function will accept a string followed by any number of integer arguments:
func foo(s string, args ...int) {
...
}
In the function body args
will be an []int
slice, so you can determine how many arguments were passed with len
, and iterate through them as you would with any other slice.
If you want to accept arguments of any type, you can use the blank interface as the type:
func bar(args ...interface{}) {
...
}
Now args
will be an []interface{}
slice. You can unpack the values passed in using a type assertion or type switch.