I'm slightly confused about the behavior of the unpack/spread operator when trying to append into a slice of empty interfaces (i.e. []interface{}
) from an slice of a custom type. I expected it to work since the interface{}
can hold any type, but I'm currently receiving errors when trying to do this operation.
The following snippet illustrates the issue:
package main
import (
"fmt"
)
type CustomType struct {
value int
}
func main() {
data := []interface{}{}
values := []CustomType{
{value: 0},
{value: 1},
}
// This does not compile:
// data = append(data, values...)
// But this works fine
data = append(data, values[0])
for _, value := range data {
fmt.Printf("Value: %v\n", value)
}
}
Go playground with the snippet above
I expected to be able to unpack the values
slice and append its elements into the data
slice since it can hold any values, but the compiler does not like that and complains about the values
array not being of []interface{}
type. When I append the values one by one, then compiler is OK with the operation.
Why is unpacking the values slice not allowed in this situation?