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

如何在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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现