I want to pass in a list of strings as generic parameters in go, but not sure if its possible. I have workarounds but feel like I'm just not able to get syntax correct.
package main
import "fmt"
func Set(otherFields ...interface{}) {
fmt.Printf("%v", otherFields)
}
func main() {
a := []string {"Abc", "def", "ghi"}
Set(a) // incorrect behavior because a passed through as a list, rather than a bunch of parameters
// Set(a...) // compiler error: cannot use a (type []string) as type []interface {} in argument to Set
// Set([]interface{}(a)) // compiler error: cannot convert a (type []string) to type []interface {}
// This works but I want to do what was above.
b := []interface{} {"Abc", "def", "ghi"}
Set(b...)
}
You have to deal with each string individually. You can't just cast the whole collection. Here's an example;
package main
import "fmt"
func main() {
a := []string {"Abc", "def", "ghi"}
b := []interface{}{} // initialize a slice of type interface{}
for _, s := range a {
b = append(b, s) // append each item in a to b
}
fmt.Println(len(b)) // prove we got em all
for _, s := range b {
fmt.Println(s) // in case you're real skeptical
}
}
https://play.golang.org/p/VWtRTm01ah
As you can see, no cast is necessary because the collection of type inferface{}
will accept any type (all types implement the empty interface Go equivalent of a void pointer in C). But you do have to deal with each item in collection individually.