The problem I’ve just faced is what to do in the following case:
func printItems(header string, items []interface{}, fmtString string) {
// ...
}
func main() {
var iarr = []int{1, 2, 3}
var farr = []float{1.0, 2.0, 3.0}
printItems("Integer array:", iarr, "")
printItems("Float array:", farr, "")
}
Go has no generics and doesn’t allow to use collection covariance:
prog.go:26: cannot use iarr (type []int) as type []interface { } in function argument
prog.go:27: cannot use farr (type []float) as type []interface { } in function argument
Ideas?
There’s not really a way to do this right now without either
[]intand[]floatboth into[]interface{}.interface{}instead of[]interface{}and then use reflection, similar to what the fmt package does.Neither solution is pretty.