【发布时间】:2019-06-20 02:41:15
【问题描述】:
编写对“通用”数组进行操作的方法的惯用方式是什么?
我有一个类型化数组:
a := make([]int, 0)
我想写一个可以操作任意类型数组的简单方法:
func reverse(a []interface{}) []interface{} {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
return a
}
使用这种方法a = reverse(a) 给了我2个错误:
cannot use a (type []int) as type []interface {} in argument to reverse
cannot use reverse(a) (type []interface {}) as type []int in assignment
【问题讨论】:
-
golang.org/doc/faq#convert_slice_of_interface。或者简而言之:你不能。你必须诉诸反思。
-
实用的解决方案是为您使用的每个具体切片类型编写一个反向函数。万一有很多类型generate the code.