Go 将泛型结构/接口传递给函数并返回它
我可以将泛型结构或接口传递到函数中,然后返回它吗?在下面的示例中,我尝试过使用指针,也尝试过使用struct作为返回类型,但似乎做不到 如果改用接口{},我似乎能够传入postData,但通过返回或更新指针将其取回似乎是不可能的。谁能告诉我哪里出了问题Go 将泛型结构/接口传递给函数并返回它,go,Go,我可以将泛型结构或接口传递到函数中,然后返回它吗?在下面的示例中,我尝试过使用指针,也尝试过使用struct作为返回类型,但似乎做不到 如果改用接口{},我似乎能够传入postData,但通过返回或更新指针将其取回似乎是不可能的。谁能告诉我哪里出了问题 func EmailHandler(writer http.ResponseWriter, request *http.Request) { var postData = EmailPostData{} ConvertReques
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)
}
完美的谢谢你为什么这样做?我假设模型接口{}需要一个星形,例如:model*interface{},以显式声明它将接受自接口{}以来任何类型的pointerjson.Unmarshal接受参数。从语义上讲,它必须是指向某个要由umarshaler填充的结构的指针。您将引用传递给postData结构,然后一切正常,您就可以使用postData了。
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
}