繁体   English   中英

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

[英]Is it possible to use reflected array type in Golang type assertions?

我需要检查interface {}是否为数组,如果是则创建相应的切片。 不幸的是我事先不知道数组的长度。

例如:

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)
}

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

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

尝试这个:

func AnythingToSlice(a interface{}) []interface{} {
    v := reflect.ValueOf(a)
    switch v.Kind() {
    case reflect.Slice, reflect.Array:
        result := make([]interface{}, v.Len())
        for i := 0; i < v.Len(); i++ {
            result[i] = v.Index(i).Interface()
        }
        return result
    default:
        panic("not supported")
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM