将 interface{} 转换为 []interface{}

如何将 interface{} 转换为 []interface{} ?


rt := reflect.ValueOf(raw)

switch rt.Kind() {

case reflect.Slice:

    src := raw.([]interface{}) //this operation errors out

    for _,_ :=  range src {

        //some operation

    }  

}

我得到一个错误panic: interface conversion: interface {} is []string, not []interface {} 我想让这个方法足够通用以处理任何类型,而不是固定类型。


我是 Go 的新手,我一直被这个问题困扰,很可能我做错了。有什么建议我怎样才能解决这个问题?


编辑: 一些操作是json.Marshal返回字节数组。


我真正想做的是: 我有一个接收接口类型的函数,如果它是一个数组/切片,那么我想在每个项目上运行 json.Marshal 而不是将它作为一个整体应用。基本上,如果第一级对象是数组,我会尝试分解 JSON blob,是的,它需要是通用的。


慕森王
浏览 81回答 1
1回答

梵蒂冈之花

如错误消息所述,a[]string不是[]interface{}. 一般使用反射 API 来执行此操作:v := reflect.ValueOf(raw)switch v.Kind() {case reflect.Slice:    for i := 0; i < v.Len(); i++ {        elem := v.Index(i).Interface()        // elem is an element of the slice    }}在 Playground 上运行它。
打开App,查看更多内容
随时随地看视频慕课网APP