任何明智的解决方案,以在Go缺乏阵列/片协方差的? [英] Any sensible solution to the lack of array/slice covariance in Go?

查看:147
本文介绍了任何明智的解决方案,以在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:不能使用IARR(类型[] INT)类型[]接口{}在函数的参数结果
  prog.go:27:不能使用法尔(键入[]浮动)类型[]接口{}在函数参数

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和[]都飘进[]接口{}

  2. 制作printItems接受接口{}而非[]接口{},然后使用反射,类似FMT包做什么。

无论解决方案是pretty。

Neither solution is pretty.

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

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