英文:
Pass uninitialized struct to a function
问题
假设我有一个处理请求体的函数:
func GetReqBody(r *http.Request) (interface{}, error) {
var data interface{}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&data)
return data, err
}
然后在控制器中,我需要进行类型断言:
func post(w http.ResponseWriter, r *http.Request) {
data, err := utils.GetReqBody(r)
// req.User 是一个结构体
newUser, ok := data.(req.User)
// ...
}
是否可能将类型断言的逻辑封装在 GetReqBody
函数中?为了做到这一点,我需要将结构体传递给函数,但由于它不是一个值,所以我无法这样做。
英文:
Let say I have a function that handles request body in general
func GetReqBody(r *http.Request) (interface {}, error){
var data interface{}
decorder := json.NewDecoder(r.Body)
decorder.DisallowUnknownFields()
err := decorder.Decode(&data)
return data, err
}
Then in the controller, I will have to do type assertion
func post(w http.ResponseWriter, r *http.Request) {
data, err := utils.GetReqBody(r)
//req.User is a struct
newUser, ok := data.(req.User)
// ...
}
Is it possible to encapsulate the type assertion login inside the GetReqBody
function? To do that I will need to pass the struct into the function, yet as it is not a value I am unable to do so.
答案1
得分: 3
在GetReqBody
函数内部封装类型断言登录是不可能的,无论如何都不可能。
然而,你可以简化你的代码如下:
func GetReqBody(r *http.Request, data interface{}) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
return decoder.Decode(data)
}
func post(w http.ResponseWriter, r *http.Request) {
var newUser req.User
if err := utils.GetReqBody(r, &newUser); err != nil {
// 处理错误
}
// ...
}
英文:
"Is it possible to encapsulate the type assertion login inside the GetReqBody
function?" -- No, it's not possible, not in any useful way.
However you could simplify your code thus:
func GetReqBody(r *http.Request, data interface{}) error {
decorder := json.NewDecoder(r.Body)
decorder.DisallowUnknownFields()
return decorder.Decode(data)
}
func post(w http.ResponseWriter, r *http.Request) {
var newUser req.User
if err := utils.GetReqBody(r, &newUser); err != nil {
// handle err
}
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论