dongshi1188 2019-02-06 00:18
浏览 508
已采纳

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

How can I cast an interface{} to []interface{} ?

rt := reflect.ValueOf(raw)
switch rt.Kind() {
case reflect.Slice:
    src := raw.([]interface{}) //this operation errors out
    for _,_ :=  range src {
        //some operation
    }  
}

I get an error panic: interface conversion: interface {} is []string, not []interface {} I want make this method generic enough to handle any type, not a fixed type.

I'm very new to Go and I'm stuck with this problem, most likely I'm doing it wrong. Any suggestion how can I get around this ?

Edit: Some operation is json.Marshal which return byte array.

What I'm really trying to do: I have a function that receives interface type, if it is an array/slice then I would like to run json.Marshal on each item rather than apply it as a whole. Basically, I'm trying to break up the JSON blob if the first level object is an array, and yes it needs to be generic.

  • 写回答

1条回答 默认 最新

  • douhuangjian9627 2019-02-06 01:54
    关注

    As the error message states, a []string is not an []interface{}. See the FAQ for an explanation.

    Use the reflect API do to this generically:

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

    Run it on the Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度