我一直在尝试实现一个可以从任何类型的切片中随机选择一个元素的函数(比如 python 的 random.choice 函数)
func RandomChoice(a []interface{}, r *rand.Rand) interface{} {
i := r.Int()%len(a)
return a[i]
}
但是,当我尝试将 []float32 类型的切片传入第一个参数时,会发生此错误:
cannot use my_array (type []float32) as type []interface {} in function argument
这是对 interface{} 的根本滥用吗?有没有更好的方法来做到这一点?