簡體   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