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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog