编译器:尽管已经提供了所有参数,但给出了太多的参数。

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

Compiler: too many arguments given despite that all are given

问题

我想使用结构体DataResponse作为JSON()的参数来响应用户。通过初始化DataResponse的实例,我得到了错误消息,说提供了太多的参数,但我已经提供了所有必要的参数。

  1. type DataResponse struct {
  2. Status int `json:"status"`
  3. Data interface{} `json:"data"`
  4. }
  5. func GetUser(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
  6. user := models.User{}
  7. // 从数据库获取用户
  8. resp := DataResponse{Status: 200, Data: user}
  9. JSON(rw, resp) // rw 是 net/http 的 ResponseWriter
  10. }

编译器抛出了以下错误消息:

  1. 转换为DataResponse的参数过多:DataResponse(200, user)

DataResponse需要两个参数,而你提供了两个参数,Data是一个接口,所以它应该接受models.User作为数据类型。

英文:

I want to use the struct DataResponse as parameter for JSON() to respond with the user. By initializing an instance of DataResponse I get the error message, that too many arguments are given, but gave all that are necessary.

<!-- language: go-lang -->

  1. type DataResponse struct {
  2. Status int `json:&quot;status&quot;`
  3. Data interface{} `json:&quot;data&quot;`
  4. }
  5. func GetUser(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
  6. user := models.User{}
  7. // Fetching user from db
  8. resp := DataResponse(200, user)
  9. JSON(rw, resp) // rw is the ResponseWriter of net/http
  10. }

The following error message is thrown by the compiler:

  1. too many arguments to conversion to DataResponse: DataResponse(200, user)

DataResponse requires two parameters that are given and Data is an interface so it should accept models.User as datatype.

答案1

得分: 36

响应的语法有误。尝试使用花括号进行结构体初始化:

  1. resp := DataResponse{200, user}
  2. ^ ^
英文:

> resp := DataResponse(200, user)

The syntax is wrong. Try curly braces for struct initialization:

  1. resp := DataResponse{200, user}
  2. ^ ^

huangapple
  • 本文由 发表于 2015年5月21日 03:04:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/30358313.html
匿名

发表评论

匿名网友

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

确定