我一直在尝试实现一个可以从任何类型的切片中随机选择一个元素的函数(比如python的random.choice函数)
func RandomChoice(a []interface{}, r *rand.Rand) interface{} {
i := r.Int()%len(a)
return a[i]
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试将一个类型为[] float32的片段传入第一个参数时,会发生以下错误:
cannot use my_array (type []float32) as type []interface {} in function argument
这是界面{}的有趣滥用吗?有没有更好的方法来做到这一点?
Re:还有更好的方法吗?
IMO有.OP方法效率低下简单:
var v []T
...
// Select a random element of 'v'
e := v[r.Intn(len(v))]
...
Run Code Online (Sandbox Code Playgroud)
请注意,这两种方法都会出现恐慌,len(v) == 0直到对此进行预先检查.