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

如何在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
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?