douji0073 2019-01-22 07:59
浏览 496
已采纳

如何将切片转换为数组?

I want to implement a method to convert a interface{} slice to a interface{} array which has equal length to the given slice. It's similar to below:

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

How can I implement this method?

EDIT: Any possible to use reflect.ArrayOf to implement this?

  • 写回答

1条回答 默认 最新

  • dqkf36241 2019-01-22 19:13
    关注

    Use 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 to copy from the slice to the array.

    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

    This function is useful for creating a map key from a slice and other scenarios where a comparable value is required. Otherwise, it's usually best to use a slice when the length can be arbitrary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?