将未初始化的结构体传递给函数。

huangapple go评论81阅读模式
英文:

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
    }

    // ...
}

huangapple
  • 本文由 发表于 2021年7月9日 21:33:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/68317694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定