将通用结构/接口传递给函数并返回

时间:2018-07-11 10:16:37

标签: go

我可以将泛型结构或接口传递给函数,然后将其返回吗?在下面的示例中,我尝试使用指针,并且还尝试使用struct作为返回类型,但是我似乎做不到。

如果我改用interface {},则似乎可以传递postData,但通过返回或更新指针似乎无法将其返回。谁能告诉我我要去哪里错了?

func EmailHandler(writer http.ResponseWriter, request *http.Request) {
    var postData = EmailPostData{}
    ConvertRequestJsonToJson(request, &postData)
}

func ConvertRequestJsonToJson(request *http.Request, model *struct{}) {
    postContent, _ := ioutil.ReadAll(request.Body)
    json.Unmarshal([]byte(postContent), &model)
}

1 个答案:

答案 0 :(得分:3)

func EmailHandler(writer http.ResponseWriter, request *http.Request) {
    var postData = EmailPostData{}
    ConvertRequestJsonToJson(request, &postData)
    //Use postData, it should be filled
}
func ConvertRequestJsonToJson(request *http.Request, model interface{}) {
    postContent, _ := ioutil.ReadAll(request.Body)
    json.Unmarshal([]byte(postContent), model)//json.Unmarshal stores the result in the value pointed to by model
}