Go 中缺少数组/切片协方差的任何明智的解决方案? [英] Any sensible solution to the lack of array/slice covariance in Go?

查看:46
本文介绍了Go 中缺少数组/切片协方差的任何明智的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚面临的问题是在以下情况下该怎么做:

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

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

想法?

推荐答案

现在没有任何方法可以做到这一点

There's not really a way to do this right now without either

  1. 使您的 []int[]float 都变成 []interface{}.
  2. 让 printItems 接受 interface{} 而不是 []interface{} 然后使用反射,类似于 fmt 包所做的.
  1. Making your []int and []float both into []interface{}.
  2. Making printItems accept interface{} instead of []interface{} and then use reflection, similar to what the fmt package does.

这两种解决方案都不是很好.

Neither solution is pretty.

这篇关于Go 中缺少数组/切片协方差的任何明智的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆