I encountered a strange error in Golang today, tangential to this question. Given the following,
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, playground")
data := []string{"A", "B", "C"}
testFunc(data...)
}
func testFunc(items ...interface{}) {
for i, item := range items {
fmt.Printf("Item %d: %v\n", i, item)
}
}
I get an error because []string
cannot be casted to []interface{}
. This makes no sense because I could do testFunc("A", "B", "C")
and it would work as expected. This tells me that the ellipsis is just a mask for a slice of the given type and so, when I call testFunc
, the compiler is comparing the slice-type with the slice-type expected by the variadic argument, and if they're not equal, returning an error. However, when sending a list of strings to the variadic argument, each string is type-checked against interface{}
instead. So, then, my question is: why does Golang do a type-check of the slice-types rather than doing an element-wise type-check?