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

如何在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 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题
  • ¥20 基于matlab的航迹融合 航迹关联 航迹插补
  • ¥15 用Matlab实现图中的光线追迹
  • ¥15 联想笔记本开机出现系统更新界面