donglue1886 2017-03-26 21:45
浏览 50
已采纳

在函数中传递接口切片并将其解编组

Can i pass into function a slice of structs, converted to []interface{}, fill it and use after function end work?

Here is full example of the problem https://play.golang.org/p/iPijsawEEg

Short describe:

type DBResponse struct {
    Rows  int             `json:"rows"`
    Error string          `json:"error"`
    Value json.RawMessage `json:"value"`
}
type User struct {
    Id   int    `json:"id"`
    Name string `json:"name"`
}

func loadDBRows(p []interface{}) {
    var response DBResponse
    someDataFromDB := []byte("{\"rows\":1, \"error\": \"\", \"value\": {\"name\":\"John\", \"id\":2}}")
    json.Unmarshal(someDataFromDB, &response)
    json.Unmarshal(response.Value, &p[0])
    fmt.Println(p)//p[0] filled with map, not object
}

func main() {
    users := make([]User, 5)
    data := make([]interface{}, 5)
    for i := range users {
        data[i] = users[i]
    }
    loadDBRows(data)
}

This problem can be easily solved for single interface{}, u can test in at full example. Why i can't solve it for slice?

I want to do it without reflect! Is there any "true way" to write universal json parser to selected data struct without reflect and map[string]interface{}? Don't want complicated code and extra operations

Thank you for help!

  • 写回答

2条回答 默认 最新

  • dongou0524 2017-03-26 22:14
    关注

    Since p is a slice of interfaces, on this line json.Unmarshal(response.Value, &p[0]) you're passing a pointer to an interface{} not to a User and since json.Unmarshal allows interfaces as the destination to which to unmarshal the data, it doesn't look under the interface{} for another type and just decodes the json into a map.

    What you can do is to have the interface{} already be a pointer to a concrete type e.g. data[i] = &users[i] then you just pass the interface{} without & to json.Unmarshal.

    func loadDBRows(p []interface{}) {
        var response DBResponse
        someDataFromDB := []byte("{\"rows\":1, \"error\": \"\", \"value\": {\"name\":\"John\", \"id\":2}}")
        json.Unmarshal(someDataFromDB, &response)
        json.Unmarshal(response.Value, p[0]) // notice the missing &
        fmt.Println(p)
    }
    
    users := make([]User, 5)
    data := make([]interface{}, 5)
    for i := range users {
        data[i] = &users[i] // notice the added &
    }
    

    https://play.golang.org/p/GEbIq9febY

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵