对于Go中缺少数组/切片协方差的任何明智解决方案?

我刚刚遇到的问题是在以下情况下该怎么办:


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没有泛型,也不允许使用集合协方差:


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

有想法吗?


紫衣仙女
浏览 212回答 3
3回答

牧羊人nacy

没有任何一种,现在真的没有办法做到这一点使您[]int和[]float双方都进入[]interface{}。使printItems接受interface{}而不是[]interface{}使用反射,然后使用反射,类似于fmt包所做的事情。两种解决方案都不是很漂亮。

呼啦一阵风

使用反射的示例:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "reflect"&nbsp; &nbsp; "strings"&nbsp; &nbsp; "container/vector")func printItems(header string, items interface{}, fmtString string) {&nbsp; &nbsp; value, ok := reflect.NewValue(items).(reflect.ArrayOrSliceValue)&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; panic("Not an array or slice")&nbsp; &nbsp; }&nbsp; &nbsp; stringBuilder := new(vector.StringVector)&nbsp; &nbsp; stringBuilder.Push(header)&nbsp; &nbsp; n := value.Len()&nbsp; &nbsp; for i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; stringBuilder.Push(fmt.Sprintf(fmtString, value.Elem(i).Interface()))&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(strings.Join(*stringBuilder, ""))}func main() {&nbsp; &nbsp; var iarr = []int{1, 2, 3}&nbsp; &nbsp; var farr = []float{1.0, 2.0, 3.0}&nbsp; &nbsp; printItems("Integer array:", iarr, " %d,")&nbsp; &nbsp; printItems("Float array:", farr, " %.1f,")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go