首页 文章

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

提问于
浏览
-1

我可以将通用结构或接口传递给函数,然后返回它吗?我已尝试在下面的示例中使用指针,我也尝试使用struct作为返回类型,但我似乎无法做到这一点 .

如果我使用接口{},我似乎能够传递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 回答

  • 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
    }
    

相关问题