为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕森王 2023-06-05 17:21:26
如何将 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,是的,它需要是通用的。
查看完整描述

1 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

如错误消息所述,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 上运行它



查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信