英文:
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:"status"`
Data interface{} `json:"data"`
}
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}
^ ^
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论