Convert []string to []interface{}
- Create a utility function, like this
func ToGenericArray(arr ...interface{}) []interface{} {
return arr
}
- And use it:
func yourfunc(arr []interface{}) {
....
}
yourfunc(ToGenericArray([...]string{"a", "b", "c"}))
- IMPORTANT NOTICE: the following will not work
func yourfunc(arr []interface{}) {
....
}
arr:=[...]string{"a", "b", "c"}
yourfunc(ToGenericArray(arr))
now I know I'm wrong,
[]type
is a whole type, can't be considered as[]interface{}
.
Yes, and that is because interface{}
is its own type (and not an "alias" for any other type).
As I mention in "what is the meaning of interface{}
in golang?" (if v
is a interface{}
variable):
Beginner gophers are led to believe that “
v
is of any type”, but that is wrong.v
is not of any type; it is ofinterface{}
type.
The FAQ mentions
they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination slice.
This example converts a slice of int to a slice ofinterface{}
:
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
Tom L propose this example (in the comments):
package main
import "fmt"
func main() {
x := []string{"a", "b", "c", "d"}
fmt.Printf("%T: %v\n", x, x)
//converting a []string to a []interface{}
y := make([]interface{}, len(x))
for i, v := range x {
y[i] = v
}
fmt.Printf("%T: %v\n", y, y)
//converting a []interface{} to a []string
z := make([]string, len(y))
for i, v := range y {
z[i] = fmt.Sprint(v)
}
fmt.Printf("%T: %v\n", z, z)
}