Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Passing an array to a function receiving argument list

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?

like image 879
Ronna Avatar asked Apr 10 '26 09:04

Ronna


1 Answers

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.

like image 189
Simon Fox Avatar answered Apr 11 '26 22:04

Simon Fox