如何将切片转换为数组?

How to convert slice to array?

我想实现一种方法,将 interface{} 切片转换为长度与给定切片相等的 interface{} 数组。它类似于以下内容:

func SliceToArray(in []interface{}) (out interface{}) {
 ...
}
// out's type is [...]interface{} and len(out)==len(in)

如何实现这个方法?

编辑: 有可能使用 reflect.ArrayOf 来实现吗?

使用reflect.ArrayOf to create the array type given the slice element type. Use reflect.New to create a value of that type. Use reflect.Copy从切片复制到数组。

func SliceToArray(in interface{}) interface{} {
    s := reflect.ValueOf(in)
    if s.Kind() != reflect.Slice {
        panic("not a slice")
    }
    t := reflect.ArrayOf(s.Len(), s.Type().Elem())
    a := reflect.New(t).Elem()
    reflect.Copy(a, s)
    return a.Interface()
}

Run it on the Playground

此函数对于从切片和其他需要可比较值的场景创建映射键很有用。否则,当长度可以任意时,通常最好使用切片。