arraysgoslicereflect

How to convert slice to array?


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?


Solution

  • 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.