How can I pass an array as interface{} argument list in go?
func Yalla(i...interface{}) {
fmt.Println(i...)
}
func main() {
Yalla(1,2,3)
Yalla([]int{1,2,3})
}
Will output:
1 2 3 //good
[1 2 3] //bad
This:
Yalla([]int{1,2,3}...)
Will generate an error.
I know I can make a new interface array and assign the values one by one to solve this, but is there an elegant way to do it?
There is no elegant shortcut for converting from an array of integers to a slice of interface{}. You need to write the for loop.
The call
Yalla([...]int{1,2,3}...)
does not compile because an array of integers and a slice of interface{} are different types. You can easily create a slice over the array using [:]:
Yalla([...]int{1,2,3}[:]...)
but this does not solve the problem because a slice of integers and a slice of interface{} are different types as explained in the FAQ.
You either need to copy the values as shown in the FAQ, start with a slice of interface{}
Yalla([]interface{}{1,2,3}...)
or change the variadic argument type to int
func Yalla(i ...int) {
}
if that's what you are always passing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With