douji4223 2019-04-30 03:31
浏览 1084
已采纳

如何在Golang中将不同类型的struct作为参数传递给函数

I have a function for decode http response json to a struct.And I have two types of structs needed to pass to this function, and have the type of struct as return value to get the decoded json.

My function now can deal with ONE type, need help to make it can handle different type of struct, and return the struct.

// Response json
type responseResult struct {
    result string
}

type loginResult struct {
    responseResult
    token string
}

func responseBodyDecoder(resp http.Response,response *responseResult) {
    // get result form Response
    decoder := json.NewDecoder(resp.Body)
    decode_err := decoder.Decode(&response)
    if decode_err != nil {
        panic(decode_err)
    }
}

  • 写回答

1条回答 默认 最新

  • duai4512 2019-04-30 04:27
    关注

    you can use type interface{}:

    func responseBodyDecoder(resp http.Response,response interface{}) {
        // get result form Response
        decoder := json.NewDecoder(resp.Body)
        decode_err := decoder.Decode(response)
        if decode_err != nil {
            panic(decode_err)
        }
    }
    

    now, you can:

    ret:=loginResult{}
    responseBodyDecoder(resp, &ret)
    
    ret2:=responseResult{}
    responseBodyDecoder(resp, &ret2)
    
    

    but careful, both struct responseResult and responseResult don't export any element. you must modify the definition:

    type responseResult struct {
        Result string
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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键失灵