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

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

Pass uninitialized struct to a function

问题

假设我有一个处理请求体的函数:

  1. func GetReqBody(r *http.Request) (interface{}, error) {
  2. var data interface{}
  3. decoder := json.NewDecoder(r.Body)
  4. decoder.DisallowUnknownFields()
  5. err := decoder.Decode(&data)
  6. return data, err
  7. }

然后在控制器中,我需要进行类型断言:

  1. func post(w http.ResponseWriter, r *http.Request) {
  2. data, err := utils.GetReqBody(r)
  3. // req.User 是一个结构体
  4. newUser, ok := data.(req.User)
  5. // ...
  6. }

是否可能将类型断言的逻辑封装在 GetReqBody 函数中?为了做到这一点,我需要将结构体传递给函数,但由于它不是一个值,所以我无法这样做。

英文:

Let say I have a function that handles request body in general

  1. func GetReqBody(r *http.Request) (interface {}, error){
  2. var data interface{}
  3. decorder := json.NewDecoder(r.Body)
  4. decorder.DisallowUnknownFields()
  5. err := decorder.Decode(&data)
  6. return data, err
  7. }

Then in the controller, I will have to do type assertion

  1. func post(w http.ResponseWriter, r *http.Request) {
  2. data, err := utils.GetReqBody(r)
  3. //req.User is a struct
  4. newUser, ok := data.(req.User)
  5. // ...
  6. }

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函数内部封装类型断言登录是不可能的,无论如何都不可能。

然而,你可以简化你的代码如下:

  1. func GetReqBody(r *http.Request, data interface{}) error {
  2. decoder := json.NewDecoder(r.Body)
  3. decoder.DisallowUnknownFields()
  4. return decoder.Decode(data)
  5. }
  1. func post(w http.ResponseWriter, r *http.Request) {
  2. var newUser req.User
  3. if err := utils.GetReqBody(r, &newUser); err != nil {
  4. // 处理错误
  5. }
  6. // ...
  7. }
英文:

"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:

  1. func GetReqBody(r *http.Request, data interface{}) error {
  2. decorder := json.NewDecoder(r.Body)
  3. decorder.DisallowUnknownFields()
  4. return decorder.Decode(data)
  5. }
  1. func post(w http.ResponseWriter, r *http.Request) {
  2. var newUser req.User
  3. if err := utils.GetReqBody(r, &newUser); err != nil {
  4. // handle err
  5. }
  6. // ...
  7. }

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:

确定