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

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

Compiler: too many arguments given despite that all are given

问题

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

type DataResponse struct {
    Status int         `json:"status"`
    Data   interface{} `json:"data"`
}

func GetUser(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
    user := models.User{}
    // 从数据库获取用户

    resp := DataResponse{Status: 200, Data: user}
    JSON(rw, resp) // rw 是 net/http 的 ResponseWriter
}

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

转换为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 -->

type DataResponse struct {
	Status int         `json:&quot;status&quot;`
	Data   interface{} `json:&quot;data&quot;`
}

func GetUser(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	user := models.User{}
	// Fetching user from db

	resp := DataResponse(200, user)
    JSON(rw, resp) // rw is the ResponseWriter of net/http
}

The following error message is thrown by the compiler:

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

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

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

> resp := DataResponse(200, user)

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

resp := DataResponse{200, user}
                    ^         ^

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:

确定