是否可以在Golang类型断言中使用反射数组类型?

时间:2017-08-15 14:03:29

标签: go

我需要检查interface {}是否是一个数组并创建相应的slice(如果是)。不幸的是我不提前知道数组长度。

例如:

import (
  "reflect"
)
func AnythingToSlice(a interface{}) []interface{} {
  rt := reflect.TypeOf(a)
  switch rt.Kind() {
  case reflect.Slice:
    slice, ok := a.([]interface{})
    if ok {
      return slice
    }
    // it works

  case reflect.Array:
    // return a[:]
    // it doesn't work: cannot slice a (type interface {})   
    //
    array, ok := a.([reflect.ValueOf(a).Len()]interface{})
    // :-((( non-constant array bound reflect.ValueOf(a).Len()
    if ok {
       return array[:]
    }

  }
  return []interface{}(a)
}

1 个答案:

答案 0 :(得分:2)

类型断言中需要显式类型。该类型不能通过反射构建。

除非参数是[] interface {},否则必须复制切片或数组以生成[]接口{}。

试试这个:

2^N-1

https://play.golang.org/p/3bXxnHOK8_

相关问题